最近学习Spring时,认识到Spring异常处理的强大。以前处理工程异常,代码中最多见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑:html
1 try{ 2 .......... 3 }catch(Exception1 e){ 4 .......... 5 }catch(Exception2 e){ 6 ........... 7 }catch(Exception3 e){ 8 ........... 9 }
Spring可以较好的处理这种问题,核心以下,文章主要关注前两个:java
源码以下:spring
1 @Target({ElementType.METHOD}) 2 @Retention(RetentionPolicy.RUNTIME) 3 @Documented 4 public @interface ExceptionHandler { 5 Class<? extends Throwable>[] value() default {}; 6 }
该注解做用对象为方法,而且在运行时有效,value()能够指定异常类。由该注解注释的方法能够具备灵活的输入参数(详细参见Spring API):api
。
Model
方法返回值能够为:spring-mvc
源码以下:mvc
1 @Target({ElementType.TYPE}) 2 @Retention(RetentionPolicy.RUNTIME) 3 @Documented 4 @Component 5 public @interface ControllerAdvice { 6 @AliasFor("basePackages") 7 String[] value() default {}; 8 9 @AliasFor("value") 10 String[] basePackages() default {}; 11 12 Class<?>[] basePackageClasses() default {}; 13 14 Class<?>[] assignableTypes() default {}; 15 16 Class<? extends Annotation>[] annotations() default {}; 17 }
该注解做用对象为TYPE,包括类、接口和枚举等,在运行时有效,而且能够经过Spring扫描为bean组件。其能够包含由@ExceptionHandler、@InitBinder 和@ModelAttribute标注的方法,能够处理多个Controller类,这样全部控制器的异常能够在一个地方进行处理。app
异常类:jsp
1 public class CustomGenericException extends RuntimeException{ 2 private static final long serialVersionUID = 1L; 3 4 private String errCode; 5 private String errMsg; 6 7 public String getErrCode() { 8 return errCode; 9 } 10 11 public void setErrCode(String errCode) { 12 this.errCode = errCode; 13 } 14 15 public String getErrMsg() { 16 return errMsg; 17 } 18 19 public void setErrMsg(String errMsg) { 20 this.errMsg = errMsg; 21 } 22 23 public CustomGenericException(String errCode, String errMsg) { 24 this.errCode = errCode; 25 this.errMsg = errMsg; 26 } 27 }
控制器:学习
1 @Controller 2 @RequestMapping("/exception") 3 public class ExceptionController { 4 5 @RequestMapping(value = "/{type}", method = RequestMethod.GET) 6 public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{ 7 if ("error".equals(type)) { 8 // 由handleCustomException处理 9 throw new CustomGenericException("E888", "This is custom message"); 10 } else if ("io-error".equals(type)) { 11 // 由handleAllException处理 12 throw new IOException(); 13 } else { 14 return new ModelAndView("index").addObject("msg", type); 15 } 16 } 17 }
异常处理类:测试
1 @ControllerAdvice 2 public class ExceptionsHandler { 3 4 @ExceptionHandler(CustomGenericException.class)//能够直接写@ExceptionHandler,不指明异常类,会自动映射 5 public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ //还能够声明接收其余任意参数 6 ModelAndView modelAndView = new ModelAndView("generic_error"); 7 modelAndView.addObject("errCode",exception.getErrCode()); 8 modelAndView.addObject("errMsg",exception.getErrMsg()); 9 return modelAndView; 10 } 11 12 @ExceptionHandler(Exception.class)//能够直接写@EceptionHandler,IOExeption继承于Exception 13 public ModelAndView allExceptionHandler(Exception exception){ 14 ModelAndView modelAndView = new ModelAndView("generic_error"); 15 modelAndView.addObject("errMsg", "this is Exception.class"); 16 return modelAndView; 17 } 18 }
JSP页面:
正常页面index.jsp:
1 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 2 <html> 3 <body> 4 <h2>Spring MVC @ExceptionHandler Example</h2> 5 6 <c:if test="${not empty msg}"> 7 <h2>${msg}</h2> 8 </c:if> 9 10 </body> 11 </html>
异常处理页面generic_error.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <body> <c:if test="${not empty errCode}"> <h1>${errCode} : System Errors</h1> </c:if> <c:if test="${empty errCode}"> <h1>System Errors</h1> </c:if> <c:if test="${not empty errMsg}"> <h2>${errMsg}</h2> </c:if> </body> </html>
测试运行以下:
正常状况:
CustomGenericException异常状况:
IOException异常状况: