SPRING MVC 异常处理 可以全局进行定义,也可以单独在SPRING controller中定义;同时SPRING MVC将异常处理的代码和业务逻辑进行分离,将异常的处理放到一个单独的带有@ExceptionHandler方法中;
@Controller
public class ExceptionController {
@RequestMapping("/exception")
public @ResponseBody String exception() {
throw new IllegalStateException("Sorry!");
}
// 处理异常的代码,这样就实现了业务逻辑和异常处理的分离
@ExceptionHandler
public @ResponseBody String handle(IllegalStateException e) {
return "IllegalStateException handled!";
}
@RequestMapping("/global-exception")
public @ResponseBody String businessException() throws BusinessException {
throw new BusinessException();
}
}
SPRING 处理异常的流程:
1.WEB启动时ExceptionHandlerExceptionResolver 扫描到通用的异常处理方法:
DEBUG ExceptionHandlerExceptionResolver Looking for exception mappings: WebApplicationContext for namespace 'appServlet-servlet': startup date [Sat Jun 08 08:40:41 GMT 2013]; parent: Root WebApplicationContext
INFO ExceptionHandlerExceptionResolver Detected @ExceptionHandler methods in globalExceptionHandler
2.当请求出现异常时,首先看当前类中是否含有@ExceptionHandler的处理方法
DEBUG ExceptionHandlerExceptionResolver Resolving exception from handler [public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.exception()]: java.lang.IllegalStateException: Sorry!
DEBUG ExceptionHandlerExceptionResolver Invoking @ExceptionHandler method: public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.handle(java.lang.IllegalStateException)
DEBUG RequestResponseBodyMethodProcessor Written [IllegalStateException handled!] as "text/plain;charset=ISO-8859-1" using [org.springframework.http.converter.StringHttpMessageConverter@163e9a1]
3.然后看有没有含有@ExceptionHandler method 的类,另外该类必须@ControllerAdvice
DEBUG ExceptionHandlerExceptionResolver Resolving exception from handler [public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.businessException() throws org.springframework.samples.mvc.exceptions.BusinessException]: org.springframework.samples.mvc.exceptions.BusinessException
DEBUG ExceptionHandlerExceptionResolver Invoking @ExceptionHandler method: public java.lang.String org.springframework.samples.mvc.exceptions.GlobalExceptionHandler.handleBusinessException(org.springframework.samples.mvc.exceptions.BusinessException)