Exception Handling in Spring: Using ControllerAdvice Annotation and ResponseBodyAdvice
--
In a Spring application, exceptions can occur at various levels, such as service, repository, or controller. Handling exceptions appropriately is crucial for providing a better user experience and improving the overall reliability of the application.
Spring provides two ways to handle exceptions: at the controller level and with the @ControllerAdvice annotation.
Handling Exceptions at the Controller Level
To handle exceptions at the controller level, we can use the @ExceptionHandler annotation. The @ExceptionHandler annotation is used to define a method that handles a specific type of exception thrown by a controller method. This method should be defined within the same controller class and annotated with the @ExceptionHandler annotation.
Here’s an example:
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
throw new RuntimeException("Oops! Something went wrong");
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + ex.getMessage());
}
}
In the above example, we have defined a controller class called MyController with a method called hello that throws a RuntimeException. We have also defined a method called handleRuntimeException, which is annotated with the @ExceptionHandler annotation and takes a RuntimeException object as an argument.
The handleRuntimeException method returns a ResponseEntity object that contains the error message and status code to be sent back to the client. In this case, we are returning a 500 Internal Server Error status code along with the error message.
If a RuntimeException is thrown in the hello method, the handleRuntimeException method in the same controller class will be invoked to handle the exception.
By using the @ExceptionHandler annotation, you can provide more specific error handling logic for individual controller methods. This allows you to handle exceptions differently depending on the context in which they occur.