java / beginner
Snippet
Centralizing API Error Handling with ControllerAdvice
Instead of catching exceptions in individual controllers, Spring provides @RestControllerAdvice to handle errors application-wide. When a controller throws ItemNotFoundException, Spring routes the exception to the corresponding @ExceptionHandler method, allowing you to return consistent, structured JSON error responses with proper HTTP status codes.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ResponseStatus(HttpStatus.NOT_FOUND)public class ItemNotFoundException extends RuntimeException {public ItemNotFoundException(String message) {super(message);}}@RestControllerAdvicepublic class GlobalApiExceptionHandler {@ExceptionHandler(ItemNotFoundException.class)public ResponseEntity<Map<String, String>> handleItemNotFound(ItemNotFoundException ex) {Map<String, String> response = new HashMap<>();response.put("error", ex.getMessage());response.put("timestamp", LocalDateTime.now().toString());return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);}}
spring
Breakdown
1
@RestControllerAdvice
Marks the class as a global interceptor for exceptions thrown across all REST controllers.
2
@ExceptionHandler(ItemNotFoundException.class)
Specifies which exception type this method is responsible for catching and handling.
3
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
Builds and sends a custom HTTP 404 response payload formatted as JSON key-value pairs.