Spring Boot FAQ: Top Questions
16. How do you handle exceptions globally in Spring Boot?
Global exception handling in Spring Boot can be done using @ControllerAdvice
and @ExceptionHandler
annotations to manage exceptions across the entire application.
πΊοΈ Step-by-Step:
- Create a class annotated with
@ControllerAdvice
. - Define methods using
@ExceptionHandler
for specific exceptions.
π₯ Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
π Expected Output:
Returns 404 status with custom error message for ResourceNotFoundException.
π οΈ Use Cases:
- Custom error responses for different exceptions.
- Centralized exception management.