当前位置: 移动技术网 > IT编程>开发语言>Java > springboot之全局处理异常封装

springboot之全局处理异常封装

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

springboot之全局处理异常封装

简介

在项目中经常出现系统异常的情况,比如nullpointerexception等等。如果默认未处理的情况下,springboot会响应默认的错误提示,这样对用户体验不是友好,系统层面的错误,用户不能感知到,即使为500的错误,可以给用户提示一个类似服务器开小差的友好提示等。

在微服务里,每个服务中都会有异常情况,几乎所有服务的默认异常处理配置一致,导致很多重复编码,我们将这些重复默认异常处理可以抽出一个公共starter包,各个服务依赖即可,定制化异常处理在各个模块里开发。

配置

unified-dispose-springboot-starter

这个模块里包含异常处理以及全局返回封装等功能,下面。

完整目录结构如下:

├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── purgetiem
│   │   │           └── starter
│   │   │               └── dispose
│   │   │                   ├── globaldefaultconfiguration.java
│   │   │                   ├── globaldefaultproperties.java
│   │   │                   ├── interceptors.java
│   │   │                   ├── result.java
│   │   │                   ├── advice
│   │   │                   │   └── commonresponsedataadvice.java
│   │   │                   ├── annotation
│   │   │                   │   ├── enableglobaldispose.java
│   │   │                   │   └── ignorreponseadvice.java
│   │   │                   └── exception
│   │   │                       ├── globaldefaultexceptionhandler.java
│   │   │                       ├── category
│   │   │                       │   └── businessexception.java
│   │   │                       └── error
│   │   │                           ├── commonerrorcode.java
│   │   │                           └── details
│   │   │                               └── businesserrorcode.java
│   │   └── resources
│   │       ├── meta-inf
│   │       │   └── spring.factories
│   │       └── dispose.properties
│   └── test
│       └── java

异常处理

@restcontrolleradvice 或者 @controlleradvicespring的异常处理注解。

我们先创建globaldefaultexceptionhandler 全局异常处理类:

@restcontrolleradvice
public class globaldefaultexceptionhandler {

  private static final logger log = loggerfactory.getlogger(globaldefaultexceptionhandler.class);

  /**
   * nohandlerfoundexception 404 异常处理
   */
  @exceptionhandler(value = nohandlerfoundexception.class)
  @responsestatus(httpstatus.not_found)
  public result handlernohandlerfoundexception(nohandlerfoundexception exception) {
    outputerrorwarn(nohandlerfoundexception.class, commonerrorcode.not_found, exception);
    return result.offail(commonerrorcode.not_found);
  }

  /**
   * httprequestmethodnotsupportedexception 405 异常处理
   */
  @exceptionhandler(httprequestmethodnotsupportedexception.class)
  public result handlerhttprequestmethodnotsupportedexception(
      httprequestmethodnotsupportedexception exception) {
    outputerrorwarn(httprequestmethodnotsupportedexception.class,
        commonerrorcode.method_not_allowed, exception);
    return result.offail(commonerrorcode.method_not_allowed);
  }

  /**
   * httpmediatypenotsupportedexception 415 异常处理
   */
  @exceptionhandler(httpmediatypenotsupportedexception.class)
  public result handlerhttpmediatypenotsupportedexception(
      httpmediatypenotsupportedexception exception) {
    outputerrorwarn(httpmediatypenotsupportedexception.class,
        commonerrorcode.unsupported_media_type, exception);
    return result.offail(commonerrorcode.unsupported_media_type);
  }

  /**
   * exception 类捕获 500 异常处理
   */
  @exceptionhandler(value = exception.class)
  public result handlerexception(exception e) {
    return ifdepthexceptiontype(e);
  }

  /**
   * 二次深度检查错误类型
   */
  private result ifdepthexceptiontype(throwable throwable) {
    throwable cause = throwable.getcause();
    if (cause instanceof clientexception) {
      return handlerclientexception((clientexception) cause);
    }
    if (cause instanceof feignexception) {
      return handlerfeignexception((feignexception) cause);
    }
    outputerror(exception.class, commonerrorcode.exception, throwable);
    return result.offail(commonerrorcode.exception);
  }

  /**
   * feignexception 类捕获
   */
  @exceptionhandler(value = feignexception.class)
  public result handlerfeignexception(feignexception e) {
    outputerror(feignexception.class, commonerrorcode.rpc_error, e);
    return result.offail(commonerrorcode.rpc_error);
  }

  /**
   * clientexception 类捕获
   */
  @exceptionhandler(value = clientexception.class)
  public result handlerclientexception(clientexception e) {
    outputerror(clientexception.class, commonerrorcode.rpc_error, e);
    return result.offail(commonerrorcode.rpc_error);
  }

  /**
   * businessexception 类捕获
   */
  @exceptionhandler(value = businessexception.class)
  public result handlerbusinessexception(businessexception e) {
    outputerror(businessexception.class, commonerrorcode.business_error, e);
    return result.offail(e.getcode(), e.getmessage());
  }

  /**
   * httpmessagenotreadableexception 参数错误异常
   */
  @exceptionhandler(httpmessagenotreadableexception.class)
  public result handlehttpmessagenotreadableexception(httpmessagenotreadableexception e) {
    outputerror(httpmessagenotreadableexception.class, commonerrorcode.param_error, e);
    string msg = string.format("%s : 错误详情( %s )", commonerrorcode.param_error.getmessage(),
        e.getrootcause().getmessage());
    return result.offail(commonerrorcode.param_error.getcode(), msg);
  }

  /**
   * bindexception 参数错误异常
   */
  @exceptionhandler(bindexception.class)
  public result handlemethodargumentnotvalidexception(bindexception e) {
    outputerror(bindexception.class, commonerrorcode.param_error, e);
    bindingresult bindingresult = e.getbindingresult();
    return getbindresultdto(bindingresult);
  }

  private result getbindresultdto(bindingresult bindingresult) {
    list<fielderror> fielderrors = bindingresult.getfielderrors();
    if (log.isdebugenabled()) {
      for (fielderror error : fielderrors) {
        log.error("{} -> {}", error.getdefaultmessage(), error.getdefaultmessage());
      }
    }

    if (fielderrors.isempty()) {
      log.error("validexceptionhandler error fielderrors is empty");
      result.offail(commonerrorcode.business_error.getcode(), "");
    }

    return result
        .offail(commonerrorcode.param_error.getcode(), fielderrors.get(0).getdefaultmessage());
  }

  public void outputerror(class errortype, enum secondaryerrortype, throwable throwable) {
    log.error("[{}] {}: {}", errortype.getsimplename(), secondaryerrortype, throwable.getmessage(),
        throwable);
  }

  public void outputerrorwarn(class errortype, enum secondaryerrortype, throwable throwable) {
    log.warn("[{}] {}: {}", errortype.getsimplename(), secondaryerrortype, throwable.getmessage());
  }

}

大致内容处理了一些项目常见的异常exception,bindexception参数异常等。

这里将默认的404405415等默认http状态码也重写了。

重写这个默认的状态码需要配置throw-exception-if-no-handler-found以及add-mappings

# 出现错误时, 直接抛出异常(便于异常统一处理,否则捕获不到404)
spring.mvc.throw-exception-if-no-handler-found=true
# 是否开启默认的资源处理,默认为true
spring.resources.add-mappings=false

ps: 请注意这两个配置会将静态资源忽略。

请产考webmvcautoconfiguration#addresourcehandlers

exception为了防止未知的异常没有防护到,默认给用户返回服务器开小差,请稍后再试等提示。

具体异常默认会以小到大去匹配。

如果抛出bindexception,自定义有bindexception就会去这个处理器里处理。没有就会走到它的父类去匹配,请参考java-异常体系

img

其他已知异常可以自己用@exceptionhandler注解进行捕获处理。

通用异常枚举

为了避免异常值不好维护,我们使用commonerrorcode枚举把常见的异常提示维护起来。

@getter
public enum commonerrorcode {

  /**
   * 404 web 服务器找不到您所请求的文件或脚本。请检查url 以确保路径正确。
   */
  not_found("cloud-404",
      string.format("哎呀,无法找到这个资源啦(%s)", httpstatus.not_found.getreasonphrase())),

  /**
   * 405 对于请求所标识的资源,不允许使用请求行中所指定的方法。请确保为所请求的资源设置了正确的 mime 类型。
   */
  method_not_allowed("cloud-405",
      string.format("请换个姿势操作试试(%s)", httpstatus.method_not_allowed.getreasonphrase())),

  /**
   * 415 unsupported media type
   */
  unsupported_media_type("cloud-415",
      string.format("呀,不支持该媒体类型(%s)", httpstatus.unsupported_media_type.getreasonphrase())),

  /**
   * 系统异常 500 服务器的内部错误
   */
  exception("cloud-500", "服务器开小差,请稍后再试"),

  /**
   * 系统限流
   */
  traffic_limiting("cloud-429", "哎呀,网络拥挤请稍后再试试"),

  /**
   * 服务调用异常
   */
  api_gateway_error("api-9999", "网络繁忙,请稍后再试"),

  /**
   * 参数错误
   */
  param_error("cloud-100", "参数错误"),

  /**
   * 业务异常
   */
  business_error("cloud-400", "业务异常"),

  /**
   * rpc调用异常
   */
  rpc_error("rpc-510", "呀,网络出问题啦!");

  private string code;

  private string message;

  commonerrorcode(string code, string message) {
    this.code = code;
    this.message = message;
  }
}

其实starter包中不建议使用@getterlombok注解,防止他人未使用lombok依赖该项目出现问题。

通用业务异常

这两个类完成基本可以正常使用异常拦截了,不过为了业务方便,我们创建一个一般通用的业务异常。

businessexception继承runtimeexception即可。

@getter
public class businessexception extends runtimeexception {

  private string code;
  private boolean isshowmsg = true;

  /**
   * 使用枚举传参
   *
   * @param errorcode 异常枚举
   */
  public businessexception(businesserrorcode errorcode) {
    super(errorcode.getmessage());
    this.code = errorcode.getcode();
  }

  /**
   * 使用自定义消息
   *
   * @param code 值
   * @param msg 详情
   */
  public businessexception(string code, string msg) {
    super(msg);
    this.code = code;
  }

}

businessexception加入globaldefaultexceptionhandler全局异常拦截。

/**
 * businessexception 类捕获
 */
@exceptionhandler(value = businessexception.class)
public result handlerbusinessexception(businessexception e) {
  outputerror(businessexception.class, commonerrorcode.business_error, e);
  return result.offail(e.getcode(), e.getmessage());
}

程序主动抛出异常可以通过下面方式:

throw new businessexception(businesserrorcode.business_error);
// 或者
throw new businessexception("cloud800","没有多余的库存");

通常不建议直接抛出通用的businessexception异常,应当在对应的模块里添加对应的领域的异常处理类以及对应的枚举错误类型。

如会员模块:
创建userexception异常类、usererrorcode枚举、以及userexceptionhandler统一拦截类。

userexception:

@data
public class userexception extends runtimeexception {

  private string code;
  private boolean isshowmsg = true;

  /**
   * 使用枚举传参
   *
   * @param errorcode 异常枚举
   */
  public userexception(usererrorcode errorcode) {
    super(errorcode.getmessage());
    this.setcode(errorcode.getcode());
  }

}

usererrorcode:

@getter
public enum usererrorcode {
    /**
     * 权限异常
     */
    not_permissions("cloud401","您没有操作权限"),
    ;

    private string code;

    private string message;

    commonerrorcode(string code, string message) {
        this.code = code;
        this.message = message;
    }
}

userexceptionhandler:

@slf4j
@restcontrolleradvice
public class userexceptionhandler {

  /**
   * userexception 类捕获
   */
  @exceptionhandler(value = userexception.class)
  public result handler(userexception e) {
    log.error(e.getmessage(), e);
    return result.offail(e.getcode(), e.getmessage());
  }

}

最后业务使用如下:

// 判断是否有权限抛出异常
throw new userexception(usererrorcode.not_permissions);

加入spring容器

最后将globaldefaultexceptionhandlerbean的方式注入spring容器。

@configuration
@enableconfigurationproperties(globaldefaultproperties.class)
@propertysource(value = "classpath:dispose.properties", encoding = "utf-8")
public class globaldefaultconfiguration {

  @bean
  public globaldefaultexceptionhandler globaldefaultexceptionhandler() {
    return new globaldefaultexceptionhandler();
  }

  @bean
  public commonresponsedataadvice commonresponsedataadvice(globaldefaultproperties globaldefaultproperties){
    return new commonresponsedataadvice(globaldefaultproperties);
  }

}

globaldefaultconfigurationresources/meta-inf/spring.factories文件下加载。

org.springframework.boot.autoconfigure.enableautoconfiguration=\
  com.purgetime.starter.dispose.globaldefaultconfiguration

不过我们这次使用注解方式开启。其他项目依赖包后,需要添加@enableglobaldispose才可以将全局拦截的特性开启。

将刚刚创建的spring.factories注释掉,创建enableglobaldispose注解。

@retention(retentionpolicy.runtime)
@target(elementtype.type)
@import(globaldefaultconfiguration.class)
public @interface enableglobaldispose {

}

使用@importglobaldefaultconfiguration导入即可。

使用

添加依赖

<dependency>
  <groupid>io.deepblueai</groupid>
  <artifactid>unified-dispose-deepblueai-starter</artifactid>
  <version>0.1.0.release</version>
</dependency>

启动类开启@enableglobaldispose注解即可。

总结

项目里很多重复的code,我们可以通过一定的方式去简化,以达到一定目的减少开发量。

示例代码地址:

作者github:
purgeyao 欢迎关注

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

相关文章:

验证码:
移动技术网