java / beginner
Snippet
Handling Custom Exceptions with Controller Advice
In Spring applications, handling errors centrally avoids repetitive try-catch blocks across controllers. The @RestControllerAdvice annotation intercepts exceptions thrown by handler methods across the entire application, while @ExceptionHandler maps a specific exception type to a structured HTTP response.
snippet.java
java
1
2
3
4
5
6
7
8
@RestControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(UserNotFoundException.class)public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());}}
spring
Breakdown
1
@RestControllerAdvice
Registers this class as a global interceptor for exceptions thrown in REST controllers.
2
@ExceptionHandler(UserNotFoundException.class)
Specifies that the method should execute when a UserNotFoundException is thrown.
3
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
Constructs and returns an HTTP 404 response with the exception message as the body.