Four Methods for SpringMVC to handle exceptions, and four methods for springmvc to handle exceptions
Springmvc can handle exceptions in three ways: 1. Define a method in a controller and annotate it with the @ ExceptionHandler annotation. (Highest priority)
@ExceptionHandler
public ModelAndView handleException(Exception exception){ ModelAndView mv = new ModelAndView( "error/500" ); mv.addObject( "ex" ,exception); return mv;
}
@ExceptionHandler public String handleException(Exception exception){ return "error/500" ; }
2. Global exception settings ( Second priority)
<! -- Convert the exception thrown by the Controller to a specific View, and map the exception to the processor --> <bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" > <! -- Defines the variable name used to obtain the exception information on the exception handling page. The default name is exception. --> <!--<property name= "exceptionAttribute" value= "ex" ></property>--> <property name= "exceptionMappings" > <props> <prop key= "java.lang.Throwable" >error/ 500 </prop> </props> </property> </bean>
3. Custom Exception Handling ( Second priority)
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println( "Custom exception processor" ); logger = LoggerFactory.getLogger(ex.getClass()); ResponseStatus responseStatus = AnnotationUtils.getAnnotation(ex.getClass(), ResponseStatus. class ); ModelAndView modelAndView = new ModelAndView( "error/500" ); // Custom exception if (responseStatus != null ) { modelAndView.setViewName( "error/" + responseStatus.value().value()); } else { // Handle other exceptions, such as sending error alarm emails and logging logger.error(ex.getMessage(), ex); } return modelAndView; }
4. customize an exception class that inherits RunTimeException (Lowest priority)
@ResponseStatus (value = HttpStatus.NOT_FOUND,reason = "No such resource" ) public class NotFoundException extends RuntimeException { }
When a custom exception is thrown, the corresponding status code is constructed. Generally, SimpleMappingExceptionResolver is set to redirect to the error page.
Best Practice: it is best to use the global SimpleMappingExceptionResolver to write logs in jsp. When fine-grained control is required, it is better to use a custom exception parser, and others may not feel useful! If any, please correct me!