@RestControllerAdvice is an annotation in the Spring Framework that provides a convenient way to handle exceptions thrown by all controllers across the entire application. This annotation combines @ControllerAdvice and @ResponseBody, enabling exception handling to be applied across multiple @Controller or @RestController components and directly serialize the response into JSON or other RESTful formats.
Main Purposes
-
Global Exception Handling:
@RestControllerAdvicecan capture various unhandled exceptions thrown at the controller layer and handle them uniformly, avoiding the need for repetitive exception handling code in each controller. -
Application Consistency: It helps maintain consistent error handling strategies across the entire application, ensuring all error responses follow the same format or structure, which facilitates frontend development and maintenance.
-
Data Transformation: Combined with
@ResponseBody, it automatically converts exception information or any return objects into JSON or other RESTful formats, facilitating interaction with the frontend.
Usage Example
Assume we are developing an e-commerce application where a user's requested product ID might not be found, typically throwing a ResourceNotFoundException. Here's how to use @RestControllerAdvice to handle this scenario:
java@RestControllerAdvice public class GlobalExceptionHandler { // Handle exception when product is not found @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException e) { // Log the exception; can use any logging framework log.error("Requested resource not found", e); // Return a 404 Not Found response return ResponseEntity .status(HttpStatus.NOT_FOUND) .body("Error: " + e.getMessage()); } // Additional exception handling methods can be added }
In this example, whenever ResourceNotFoundException is thrown in any controller, the handleResourceNotFound method in the GlobalExceptionHandler class will capture it and return a uniformly formatted 404 response. This significantly improves code reusability and maintainability.