/** * Interface to be implemented by objects that can resolve exceptions thrown during * handler mapping or execution, in the typical case to error views. Implementors are * typically registered as beans in the application context. * * <p>Error views are analogous to JSP error pages but can be used with any kind of * exception including any checked exception, with potentially fine-grained mappings for * specific handlers. * * @author Juergen Hoeller * @since 22.11.2003 */ public interface HandlerExceptionResolver {
/** * Try to resolve the given exception that got thrown during handler execution, * returning a {@link ModelAndView} that represents a specific error page if appropriate. * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty} * to indicate that the exception has been resolved successfully but that no view * should be rendered, for instance by setting a status code. * @param request current HTTP request * @param response current HTTP response * @param handler the executed handler, or {@code null} if none chosen at the * time of the exception (for example, if multipart resolution failed) * @param ex the exception that got thrown during handler execution * @return a corresponding {@code ModelAndView} to forward to, or {@code null} * for default processing */ ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
@ControllerAdvice public class HandlerExceptionController { @ExceptionHandler({ArithmeticException.class,IOException.class}) public ModelAndView TestExceptionHandlerExceptionResolver(Exception ex){ System.out.println("03----ControllerAdvice出异常了:"+ex); ModelAndView model = new ModelAndView("error"); model.addObject("exception", ex); return model; } }
ResponseStatusExceptionResolver
用于解析 当抛出自定义的异常(该异常用@ResponseStatus注解)时,对客户端响应。
1 2 3 4 5 6 7 8
//自定义异常类 //reason: 指定显示信息 //value: http的状状态码 //不要标在方法上面,尽管可以,会造成应该正常的显示页面也产生错误页面上 @ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户名与密码不匹配") public class NameNOTINPasswordException extends RuntimeException { private static final long serialVersionUID = 1L; }
1 2 3 4 5 6 7 8 9 10
// 测试ResponseStatusExceptionResolver 注意自定义异常类NameNOTINPasswordException @RequestMapping("TestResponseStatusExceptionResolver") public String TestResponseStatusExceptionResolver(@RequestParam("i") int i){ if(i==13 ){ throw new NameNOTINPasswordException(); // 更改浏览器参数i为13 // throw new RuntimeErrorException(null); } System.out.println("TestResponseStatusExceptionResolver ..."); return "success"; }