springmvc中是有默认的异常处理机制的,但是我们也可以自定义异常处理。 主要有:@ControllerAdvice 、@ResponseStatus 、@ExceptionHandler 1、三种处理机制的使用 @ControllerAdvice:异常处理全局配置 @ResponseStatus:可定义在方法上也可以定义在类上,一般定义在类上 @ExceptionHandler:定义于方法上 2、处理机制的优先级 每次在找异常处理时,先在本类中查找,然后再找全局配置 (1)优先级若在三种处理机制都定义的情况下,会优先找@ExceptionHandler ,因为此注解定义与类中,而类中若定义多个@ExceptionHandler ,会先找小范围再找大范围 (2)若没有@ExceptionHandler,会先找@ControllerAdvice ,,同样未全局配置情况下,springmvc会先找@ControllerAdvice 。
代码部分 (1)@ExceptionHandler 与@ResponseStatus 的类中应用
@Controller
public class ExceptionController {
@RequestMapping("/exception1")
public String exception(){
System.out.println(this.getClass().getName());
int i = 1/0;
return "success";
}
@ResponseStatus(value = HttpStatus.OK,reason = "错了就是错了")
@RequestMapping("/exception2")
public String exception2() {
System.out.println(this.getClass().getName());
return "success";
}
@RequestMapping("/exception3")
public String exception3(String username) {
System.out.println(this.getClass().getName());
if(("admin").equals(username)){
return "success";
}else {
throw new UsernameException();
}
}
@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView handlerException(Exception exception){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
modelAndView.addObject("exce",exception);
return modelAndView;
}
@ExceptionHandler(value = {NullPointerException.class,Exception.class})
public ModelAndView handlerException2(Exception exception){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
modelAndView.addObject("exce",exception);
return modelAndView;
}
}
(2)@ResponseStatus的全局配置
@ResponseStatus(reason = "出错了",value = HttpStatus.NOT_ACCEPTABLE)
public class UsernameException extends RuntimeException{
}
(3)@ControllerAdvice 的应用
@ControllerAdvice
public class MyGlobalController {
@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView handlerException(Exception exception){
ModelAndView modelAndView = new ModelAndView();
System.out.println("global");
modelAndView.setViewName("error");
modelAndView.addObject("exce",exception);
return modelAndView;
}
}
|