java / intermediate
Snippet
Centralized Error Handling with @RestControllerAdvice
In Spring Boot, @RestControllerAdvice is used to handle exceptions globally across the entire application. Instead of putting try-catch blocks in every controller, this component intercepts specific exceptions and returns a consistent response format to the client.
snippet.java
1
2
3
4
5
6
7
@RestControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(UserNotFoundException.class)public ResponseEntity<String> handleNotFound(UserNotFoundException ex) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());}}
spring
Breakdown
1
@RestControllerAdvice
Indicates that this class provides centralized exception handling for all REST controllers.
2
@ExceptionHandler(UserNotFoundException.class)
Specifies that the following method should handle occurrences of UserNotFoundException.