java / beginner
Snippet
Global Exception Handling
@ControllerAdvice allows you to handle exceptions across the whole application in one central place, providing a consistent API response format.
snippet.java
1
2
3
4
5
6
7
8
@ControllerAdvicepublic class GlobalHandler {@ExceptionHandler(ResourceNotFoundException.class)public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {return ResponseEntity.status(404).body(ex.getMessage());}}
spring
Breakdown
1
@ControllerAdvice
Intercepts exceptions from all controllers globally.
2
@ExceptionHandler
Specificies which exception type this method should catch and process.