Spring Boot Exception Handling
Implementing Global Exception Handling:
- Use
@ControllerAdvice
and@ExceptionHandler
to handle exceptions globally.
Example: Custom Exception for Resource Not Found
Create a
ResourceNotFoundException
Class:java
package com.example.demo; public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } }
Handle Exception in Controller:
java
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductRepository productRepository; @GetMapping("/{id}") public ResponseEntity<Product> getProduct(@PathVariable Long id) { Product product = productRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Product not found")); return ResponseEntity.ok(product); } // Other CRUD methods... }
Create a Global Exception Handler:
java
package com.example.demo; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } // Other exception handlers... }