How to handle exceptions in Spring MVC Framework?
How to handle exceptions in Spring MVC Framework?
Handling exceptions in the Spring MVC framework is a crucial aspect of building robust and user-friendly web applications. The framework provides several mechanisms to manage exceptions gracefully. Below, I'll outline the primary methods used to handle exceptions in Spring MVC, focusing on the use of annotations like @ExceptionHandler
, @ControllerAdvice
, and the HandlerExceptionResolver
interface.
@ExceptionHandler
AnnotationThe @ExceptionHandler
annotation is used within a controller to handle exceptions specifically for the methods within that controller. When an exception is thrown, the annotated method that matches the exception type is invoked, and it can return a view or a response entity indicating an error.
For example, you can handle a NullPointerException
as follows:
@Controller
public class MyController {
@RequestMapping("/somePath")
public String someMethod() {
// some code that might throw NullPointerException
}
@ExceptionHandler(NullPointerException.class)
public ModelAndView handleNullPointerException(NullPointerException ex) {
ModelAndView model = new ModelAndView("errorPage");
model.addObject("message", ex.getMessage());
return model;
}
}
This method is specific to the controller in which it is declared[1][3].
@ControllerAdvice
Annotation@ControllerAdvice
is a more global approach to exception handling. It allows you to write a global code that can handle exceptions from multiple controllers across the application. Methods inside a class annotated with @ControllerAdvice
can also use @ExceptionHandler
to handle exceptions globally.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
}
This approach is beneficial for handling exceptions across different controllers in a centralized manner[1][4][5].
HandlerExceptionResolver
InterfaceFor more control over the exception handling process, you can implement the HandlerExceptionResolver
interface. This allows for resolving exceptions that are not handled by @ExceptionHandler
or @ControllerAdvice
. It is particularly useful for handling exceptions in a more generic way or when you have specific requirements that the annotations cannot fulfill.
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView("...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào