java / intermediate
Snippet
Global Error Handling with @ControllerAdvice
Using @ControllerAdvice allows you to handle exceptions globally across all controllers in a single class, separating error logic from business logic.
snippet.java
1
2
3
4
5
6
7
@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(NullPointerException.class)public String handleNullPointer(NullPointerException ex) {return "errors/null-reference";}}
spring
Breakdown
1
@ControllerAdvice
Specialization of @Component for classes that declare @ExceptionHandler methods to be shared across multiple @Controller classes.
2
@ExceptionHandler(...)
Annotation for handling specific exceptions in handler classes or methods.