Spring异常处理

  • @ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度

  • @ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开

  • @ResponseStatus:可以将某种异常映射为HTTP状态码

    @ControllerAdvice public class ExceptionsHandler {

    //可以直接写@ExceptionHandler,不指明异常类,会自动映射
    @ExceptionHandler(CustomGenericException.class)
    public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ 
        //还可以声明接收其他任意参数
        ModelAndView modelAndView = new ModelAndView("generic_error");
        modelAndView.addObject("errCode",exception.getErrCode());
        modelAndView.addObject("errMsg",exception.getErrMsg());
        return modelAndView;
    }
    
    @ExceptionHandler(Exception.class)//可以直接写@EceptionHandler,IOExeption继承于Exception
    public ModelAndView allExceptionHandler(Exception exception){
        ModelAndView modelAndView = new ModelAndView("generic_error");
        modelAndView.addObject("errMsg", "this is Exception.class");
        return modelAndView;
    }
    

    }

1、@ExceptionHandler

2、@ControllerAdvice

3、@ResponseStatus

@Controller
@RequestMapping("/exception")
public class ExceptionController {

    @RequestMapping(value = "/{type}", method = RequestMethod.GET)
    public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
        if ("error".equals(type)) {
            // 由handleCustomException处理
            throw new CustomGenericException("E888", "This is custom message");
        } else if ("io-error".equals(type)) {
            // 由handleAllException处理
            throw new IOException();
        } else {
            return new ModelAndView("index").addObject("msg", type);
        }
    }
}

4、HandlerExceptionResolver

  • Spring MVC提供的非常好的通用异常处理工具
  • 只能处理请求过程中抛出的异常
  • 异常处理本身所抛出的异常 、视图解析过程中抛出的异常 :不能处理
  • 可以存在多个实现了HandlerExceptionResolver的异常处理类
  • 执行顺序,由其order属性决定, order值越小,越是优先执行
  • 执行到第一个返回不是null的ModelAndView的Resolver时,结束

5、mvc:annotation-driven/自动将以下三个配置到Spring MVC

  • HandlerExceptionResolver:优先级最高
  • ResponseStatusExceptionResolver:第二
  • DefaultHandlerExceptionResolver:最低
  • SimpleMappingExceptionResolver:需要自己配置

评论

暂无评论