ControllerAdvice Annotation - SirajChaudhary/comprehensive-example-on-microservices-using-spring-boot-with-spring-cloud GitHub Wiki
Exception Handling
- Global Exception Handling
- Custom Exception Handling
A controller advice (@ControllerAdvice) allows you exception handling across the whole application, not just to an individual controller. You can think of them as an annotation driven interceptor thrown by methods annotated with @RequestMapping and similar.
Step1: Create a controller advice class and mark it with '@ControllerAdvice' annotaiton
Step2: Create exception handler methods for different in-built and custom exceptions
Example: exception handler method for in-built exception (NoSuchElementException) so now whenever NoSuchElementException is thrown this handler method will be called.
@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity<Map<String, Object>> handleNoSuchElementException(
NoSuchElementException noSuchElementException) {
Map<String, Object> body = new LinkedHashMap<>();
body.put(TIMESTAMP, LocalDateTime.now()); // NOSONAR
body.put(MESSAGE, "Pilot not found for this id"); // NOSONAR
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
Example: exception handler method for custom exception (PilotCustomException) so now whenever PilotCustomException is thrown this handler method will be called.
@ExceptionHandler(PilotCustomException.class)
public ResponseEntity<Map<String, Object>> handlePilotCustomException(PilotCustomException pilotCustomException) {
Map<String, Object> body = new LinkedHashMap<>();
body.put(TIMESTAMP, LocalDateTime.now()); // NOSONAR
body.put(MESSAGE, pilotCustomException.getErrorMessage()); // NOSONAR
body.put(STATUS, pilotCustomException.getErrorCode()); // NOSONAR
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
We can create our own custom exception having custom error message, custom error code and other fields.
Step1: Create a custom exception class
Step2: Create a exception handler method in a controller advice class (global exception handler) for the custom exception
Step3: Call/Throw custom exception
Whenever a custom exception is thrown the appropriate exception handler method of controller advice class will be called.