用@ExceptionHandler 来进行异常处理

来源:互联网 发布:windows驱动开发培训 编辑:程序博客网 时间:2024/04/26 11:23

有时候我们想统一处理一个Controller中抛出的异常怎么搞呢?

直接在Controller里面加上用@ExceptionHandler标注一个处理异常的方法像下面这样子

@ExceptionHandler(MissingServletRequestParameterException.class)@ResponseStatus(HttpStatus.BAD_REQUEST)public void processMethod(MissingServletRequestParameterException ex,HttpServletRequest request ,HttpServletResponse response) throws IOException {    System.out.println("抛异常了!"+ex.getLocalizedMessage());    logger.error("抛异常了!"+ex.getLocalizedMessage());    response.getWriter().printf(ex.getMessage());    response.flushBuffer();}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这样,Controller里面的方法抛出了MissingServletRequestParameterException异常就会执行上面的这个方法来进行异常处理。 
像我下面的代码

@RequestMapping("/index")public String index(@MyUser User user,@RequestParam String id,ModelMap modelMap){    return "login";}
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

如果我没有传入id值,那么就会抛出MissingServletRequestParameterException的异常,就会被上面的异常处理方法处理。

上面的@ExceptionHandler(MissingServletRequestParameterException.class)这个注解的value的值是一个Class[]类型的,这里的ExceptionClass是你自己指定的,你也可以指定多个需要处理的异常类型,比如这样@ExceptionHandler(value = {MissingServletRequestParameterException.class,BindException.class}),这样就会处理多个异常了。

但这个只会是在当前的Controller里面起作用,如果想在所有的Controller里面统一处理异常的话,可以用@ControllerAdvice来创建一个专门处理的类。

0 0
原创粉丝点击