当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot使用统一异常处理详解

SpringBoot使用统一异常处理详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

场景:针对异常处理,我们原来的做法是一般在最外层捕获异常即可,例如在controller中

@controller
public class hellocontroller {
 
  private static final logger logger = loggerfactory.getlogger(hellocontroller.class);
 
  @getmapping(value = "/hello")
  @responsebody
  public result hello() {
    try {
      //todo 具体的逻辑省略……
    } catch (exception e) {
      logger.error("hello接口异常={}", e);
      return resultutil.success(-1, "system error", null);
    }
    return resultutil.success(0, "success", null);
  }
}

这样的话也能解决部分问题,但是无法获取到自己指定的异常,引入全局统一异常处理的话将会极大的改善代码,减少冗余代码的产生。

自定义异常类:注意要继承自runtimeexception而不是exception,继承自exception的话,当抛出自定义异常时spring事务不会回滚

public class globalexception extends runtimeexception {
 
  private integer code; //因为我需要将异常信息也返回给接口中,所以添加code区分
 
  public globalexception(integer code,string message) {
    super(message);  //把自定义的message传递个异常父类
    this.code = code;
  }
 
  public integer getcode() {
    return code;
  }
 
  public void setcode(integer code) {
    this.code = code;
  }
}

自定义统一异常处理器:比较关键的两个注解@controlleradvice、@exceptionhandler

@controlleradvice
public class exceptionhandle {
 
  @responsebody  //因为我需要将抛出的异常返回给接口,所以加上此注解
  @exceptionhandler
  public result handle(exception e) {
    if (e instanceof globalexception) {
      globalexception ge = (globalexception) e;
      return resultutil.success1(ge.getcode(), ge.getmessage());
    }
    return resultutil.success1(-1, "system error!");
  }
 
}

写个测试类测试下

@getmapping(value = "/hello1")
@responsebody
public result hello(@requestparam(value = "age", defaultvalue = "50", required = false) integer age) throws globalexception {
  if (age < 10) {
    throw new globalexception(constantenum.less10.getcode(), constantenum.less10.getmsg());
  } else if (age > 50) {
    throw new globalexception(constantenum.more50.getcode(), constantenum.more50.getmsg());
  } else {
    return resultutil.success1(0, "success");
  }
}

把code、message封装在了constantenum枚举里面,方便统一维护

public enum constantenum {
 
  error(-1, "system error!"),
  success(100, "success"),
  less10(101, "自定义异常信息-我小于10岁"),
  more50(5001, "自定义异常信息-我大于50岁");
 
  private integer code;
  private string msg;
 
  public integer getcode() {
    return code;
  }
 
  public string getmsg() {
    return msg;
  }
 
  constantenum(integer code, string msg) {
    this.code = code;
    this.msg = msg;
  }
}


这样就实现了全局的统一异常处理,非常方便且优雅,快快在你的项目中用起来吧!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网