1.HandlerExceptionResolver
- Spring MVC 通过 HandlerExceptionResolver 处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。
在 springmvc.xml 中配置 自动装配 ExceptionHandlerExceptionResolver
2.ExceptionHandlerExceptionResolver
Controller 代码:
@ExceptionHandler(value= {RuntimeException.class})
public ModelAndView handleArithmeticException2(Exception e) {
System.out.println("[出错了] : "+ e);
//返回的视图
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("exception", e);
return modelAndView;
}
@ExceptionHandler(value= {ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception e) {
System.out.println("出错了 : "+ e);
//返回的视图
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("exception", e);
return modelAndView;
}
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") Integer i) {
//制造异常
System.out.println(10/i);
return "success";
}
注意:
以上代码中标记了两个异常处理,一个是 ArithmeticException 另一个是RuntimeException。
当在testExceptionHandlerExceptionResolver 方法中发生异常时,发生是算术异常,因此 @ExceptionHandler(value={ArithmeticException.class}) 标记的方法优先级高,如果此时没有该标记的方法则交由上面 @ExceptionHandler(value={RuntimeException.class}) 标记的方法处理。
如果在当前 Controller 中没有找到 @ExceptionHandler 注解的话,再找由 @ControllerAdvice 标记的类中 @ExceptionHandler 注解方法。
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class SpringMVCExceptionHandl {
@ExceptionHandler(value= {ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception e) {
System.out.println("--->出错了 : "+ e);
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("exception", e);
return modelAndView;
}
}
@ExceptionHandler 方法的入参不能传入 Map,若希望把异常信息传入到页面上,需要使用 ModelAndView。
<body>
<h4>Error Page</h4><br>
${requestScope.exception }
</body
3.ResponseStatusExceptionResolver
自定义一个异常类并使用 @ResponseStatus 注解
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户名和密码不匹配")
public class UserNameNotMatchPasswordException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
Controller 代码:
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i) {
if(i > 10) {
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver...");
return SUCCESS;
}
JSP:
<a href="springmvc/testResponseStatusExceptionResolver?i=11">Test ResponseStatusExceptionResolver</a>