java / intermediate
Snippet
Global Exception Handling with @ControllerAdvice
Using @ControllerAdvice allows you to handle exceptions across the entire application in one central place. This separates error logic from business logic.
snippet.java
1
2
3
4
5
6
7
8
9
@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(UserNotFoundException.class)public ResponseEntity<ErrorResponse> handleNotFound(UserNotFoundException ex) {ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage());return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);}}
spring
Breakdown
1
@ControllerAdvice
Specialized @Component that allows handling exceptions across multiple @Controller classes.
2
@ExceptionHandler(UserNotFoundException.class)
Defines which specific exception type this method should catch and handle.