In a Spring MVC application, exceptions can be handled in a centralized manner using the ‘@ExceptionHandler‘ and ‘@ControllerAdvice‘ annotations.
‘@ExceptionHandler‘ is an annotation used to handle exceptions thrown from a specific controller method. When an exception is thrown, Spring MVC looks for a method annotated with ‘@ExceptionHandler‘ in the controller class and invokes it.
‘@ControllerAdvice‘ is an annotation used to define a class that provides global exception handling for all controllers. This class can contain multiple ‘@ExceptionHandler‘ methods that handle different types of exceptions.
To handle exceptions using ‘@ExceptionHandler‘ and ‘@ControllerAdvice‘, follow these steps:
1. Implement a method annotated with ‘@ExceptionHandler‘ in the controller class to handle the specific exception. For example:
@RestController
public class MyController {
@ExceptionHandler(MyException.class)
public ResponseEntity<String> handleMyException(MyException ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/foo")
public String foo() throws MyException {
throw new MyException("Something went wrong");
}
}
In this example, ‘MyException‘ is a custom exception that extends ‘Exception‘. When the ‘/foo‘ endpoint is called, it throws ‘MyException‘. The ‘handleMyException‘ method handles this exception and returns an error response.
2. Implement a class annotated with ‘@ControllerAdvice‘ to handle global exceptions. For example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
In this example, ‘GlobalExceptionHandler‘ is a class that handles all exceptions thrown by any controller by implementing a method annotated with ‘@ExceptionHandler‘. The ‘handleException‘ method handles all exceptions by returning an error response.
3. Test the exception handling by calling the controller method that throws the exception. For example, make a call to ‘http://localhost:8080/foo‘. In this case, the ‘handleMyException‘ method in the controller class will handle the exception and return an error response.
If no ‘@ExceptionHandler‘ method is found in the controller class for a specific exception, Spring MVC searches for a matching method in the ‘@ControllerAdvice‘ class. If no matching method is found, Spring MVC returns a default error response.
In conclusion, using ‘@ExceptionHandler‘ and ‘@ControllerAdvice‘ is a powerful way to handle exceptions in a Spring MVC application. It allows developers to centralize exception handling logic and makes it easier to maintain and debug the application.