java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring的异常处理

Spring的异常处理@ExceptionHandler注解解析

作者:云川之下

这篇文章主要介绍了Spring的异常处理@ExceptionHandler注解解析,当一个Controller中有方法加了@ExceptionHandler之后,这个Controller其他方法中没有捕获的异常就会以参数的形式传入加了@ExceptionHandler注解的那个方法中,需要的朋友可以参考下

Spring的异常处理

为什么需要对异常进行处理?

假如SpringMvc我们不对异常进行任何处理, 界面上显示的是这样的,假设进行除计算,除数是0会报错.:

在这里插入图片描述

方法一 @ExceptionHandler

当一个Controller中有方法加了@ExceptionHandler之后,这个Controller其他方法中没有捕获的异常就会以参数的形式传入加了@ExceptionHandler注解的那个方法中。

@Controller
@RequestMapping("/testController")
public class TestController {
    @RequestMapping("/demo1")
    @ResponseBody
    public Object demo1(){
       //不需要try {} catch {}
        int i = 1 / 0;
        return new Date();
    }
  //TestController 内的任何异常都会被兜住
    @ExceptionHandler({RuntimeException.class})
    public ModelAndView fix(Exception ex){
        System.out.println("do This");
        return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
    }
}

注意事项:

Ambiguous @ExceptionHandler method mapped for;

方法返回值可以为:

ModelAndView对象
Model对象
Map对象
View对象
String对象
还有@ResponseBody、HttpEntity<?>或ResponseEntity<?>,以及void

缺点: 几乎所有的Controller都需要进行异常处理,于是每个Controller都需要去写一个方法,不太方便

方法二 @ControllerAdvice+@ExceptionHandler

@ControllerAdvice注解声明一个注解类,这个注解类中的方法的某些注解会应用到所有的Controller里,其中就包括@ExceptionHandler注解。

/**
 * Created by liuruijie on 2016/12/28.
 * 全局异常处理,捕获所有Controller中抛出的异常。
 */
@ControllerAdvice
public class GlobalExceptionHandler {
   //处理自定义的异常
   @ExceptionHandler(SystemException.class) 
   @ResponseBody
   public Object customHandler(SystemException e){
      e.printStackTrace();
      return WebResult.buildResult().status(e.getCode()).msg(e.getMessage());
   }
   //其他未处理的异常
   @ExceptionHandler(Exception.class)
   @ResponseBody
   public Object exceptionHandler(Exception e){
      e.printStackTrace();
      return WebResult.buildResult().status(Config.FAIL).msg("系统错误");
   }
}

到此这篇关于Spring的异常处理@ExceptionHandler注解解析的文章就介绍到这了,更多相关Spring的异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文