java / beginner
Snippet
Handling Specific Custom Exceptions with ExceptionHandler
In Spring Boot, the @ExceptionHandler annotation allows you to intercept specific Java exceptions thrown anywhere in your web layer. Instead of returning raw stack traces to users, you can return clean error objects with standard HTTP status codes.
snippet.java
java
1
2
3
4
5
6
7
8
9
@RestControllerAdvicepublic class GlobalErrorHandler {@ExceptionHandler(UserNotFoundException.class)@ResponseStatus(HttpStatus.NOT_FOUND)public Map<String, String> handleUserNotFound(UserNotFoundException ex) {return Map.of("error", ex.getMessage());}}
spring
Breakdown
1
@RestControllerAdvice
Registers this class as a global interceptor for exceptions thrown across all REST controllers.
2
@ExceptionHandler(UserNotFoundException.class)
Tells Spring to execute this method whenever a UserNotFoundException is thrown.
3
@ResponseStatus(HttpStatus.NOT_FOUND)
Automatically sets the HTTP response status code to 404 (Not Found).
4
return Map.of("error", ex.getMessage());
Constructs and returns a JSON payload containing the error description.