本文共 3252 字,大约阅读时间需要 10 分钟。
1、异常处理
2、HandlerExceptionResolver
2)使用了 <mvc:annotation-driven/>配置:
2)使用了 <mvc:annotation-driven/> 配置:
3、ExceptionHandlerExceptionResolver
@RequestMapping(value = "/testExceptionHandlerExceptionResolver") public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){ System.out.println("result:"+(10/i)); return "success"; } /** * 1、在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数,该参数即对应发生的异常对象 * 2、 @ExceptionHandler 方法的入参中不能传入Map ,若希望把异常信息传到页面上,需要使用 ModelAndView作为返回值 * 3、@ExceptionHandler 方法标记的异常有优先级的问题 * 4、@ControllerAdvice 如果在当前 Handler中找不到 @ ExceptionHandler 方法来处理当前方法的异常,将去 * @ControllerAdvice标记的类中查找来处理异常 * @param ex * @return */ @ExceptionHandler({ArithmeticException.class}) public ModelAndView handlerArithmeticExceprion(Exception ex){ System.out.println("出异常了:"+ex); ModelAndView mv = new ModelAndView("error"); mv.addObject("ex",ex); return mv; }
@ControllerAdvicepublic class Exception { @ExceptionHandler({ArithmeticException.class}) public ModelAndView handlerArithmeticExceprion(java.lang.Exception ex){ System.out.println("出异常了!!!:"+ex); ModelAndView mv = new ModelAndView("error"); mv.addObject("ex",ex); return mv; }}
4、ResponseStatusExceptionResolver
若在处理器方法上抛出了上述异常:
若 ExceptionHandlerExceptionResolver 不解析上述异常。由于触发的异常 UnauthorizedException 带有 @ResponseStatus注解。因此会被 ResponseStatusExceptionResolver解析到。最后影响 HttpStatus.UNAUTHORIZED代码给客户端。HttpStatus.UNAUTHORIZED代表响应码401,无权限。关于其他的响应码参考 HttpStatus枚举类型源码。@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "不匹配")public class NotMatchException extends RuntimeException {}
@RequestMapping(value = "/responseStatusExceptionResolver") public String responseStatusExceptionResolver(@RequestParam("i") int i){ if (i==13){ throw new NotMatchException(); } System.out.println("responseStatusExceptionResolver"); return "success"; }
5、DefaultHandlerExceptionResolver
对一些特殊的异常进行处理,比如NoSuchRequestHandlingMethodException、HttpRequestMethodNotSupportedException、HttpMediaTypeNotSupportedException、HttpMediaTypeNotAcceptableException等。
6、SimpleMappingExceptionResolver
如果希望对所有的异常进行统一的处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告。
@RequestMapping(value = "SimpleMappingExceptionResolver") public String SimpleMappingExceptionResolver(@RequestParam("i") int i){ String[] vals = new String [10]; System.out.println(vals[i]); return "success"; }
error