不要再满屏写 try...catch 了!这个更香!

简介: 不要再满屏写 try...catch 了!这个更香!

前言

软件开发springboot项目过程中,不可避免的需要处理各种异常,spring mvc 架构中各层会出现大量的try {...} catch {...} finally {...}代码块,不仅有大量的冗余代码,而且还影响代码的可读性。这样就需要定义个全局统一异常处理器,以便业务层再也不必处理异常。推荐理由

  • 代码复制到项目中通过简单的配置即可实现
  • 可以灵活的根据自己的业务异常进行更细粒度的扩展

实践

1 封装统一返回结果类

实现代码:

publicclassAjaxResult {

//是否成功

   private Boolean success;

   //状态码

   private Integer code;

   //提示信息

   private String msg;

   //数据

   private Object data;

   publicAjaxResult() {


   }

   //自定义返回结果的构造方法

   publicAjaxResult(Boolean success,Integer code, String msg,Object data) {

       this.success = success;

       this.code = code;

       this.msg = msg;

       this.data = data;

   }

   //自定义异常返回的结果

   publicstatic AjaxResult defineError(BusinessException de){

    AjaxResult result = new AjaxResult();

       result.setSuccess(false);

       result.setCode(de.getErrorCode());

       result.setMsg(de.getErrorMsg());

       result.setData(null);

       return result;

   }

   //其他异常处理方法返回的结果

   publicstatic AjaxResult otherError(ErrorEnum errorEnum){

    AjaxResult result = new AjaxResult();

       result.setMsg(errorEnum.getErrorMsg());

       result.setCode(errorEnum.getErrorCode());

       result.setSuccess(false);

       result.setData(null);

       return result;

   }


  // 省略getter/setter方法

}

2 自定义异常封装类

实现源码:

publicclassBusinessExceptionextendsRuntimeException {

privatestaticfinallong serialVersionUID = 1L;

/**
 * 错误状态码
 */

protected Integer errorCode;

/**
 * 错误提示
 */

protected String errorMsg;


publicBusinessException(){}


publicBusinessException(Integer errorCode, String errorMsg) {

        this.errorCode = errorCode;

        this.errorMsg = errorMsg;

    }


public Integer getErrorCode() {

 return errorCode;

}


publicvoidsetErrorCode(Integer errorCode) {

 this.errorCode = errorCode;

}


public String getErrorMsg() {

 return errorMsg;

}


publicvoidsetErrorMsg(String errorMsg) {

 this.errorMsg = errorMsg;

}

}

3 错误枚举,拒绝硬编码

publicenum ErrorEnum {

// 数据操作错误定义

SUCCESS(200, "成功"),

NO_PERMISSION(403,"你没得权限"),

NO_AUTH(401,"未登录"),

NOT_FOUND(404, "未找到该资源!"),

INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员"),

;


/** 错误码 */

private Integer errorCode;


/** 错误信息 */

private String errorMsg;


ErrorEnum(Integer errorCode, String errorMsg) {

 this.errorCode = errorCode;

 this.errorMsg = errorMsg;

}


   public Integer getErrorCode() {

       return errorCode;

   }


   public String getErrorMsg() {

       return errorMsg;

   }

}

4 全局异常处理类

/**
* 全局异常处理器
*
*/

@RestControllerAdvice

publicclassGlobalExceptionHandler{

   privatestaticfinal Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


   /**
    * 处理自定义异常
    *
    */

   @ExceptionHandler(value = BusinessException.class)
   publicAjaxResultbizExceptionHandler(BusinessExceptione)
{

    log.error(e.getMessage(), e);

       return AjaxResult.defineError(e);

   }


   /**
    *处理其他异常
    *
    */

   @ExceptionHandler(value = Exception.class)
   publicAjaxResultexceptionHandler( Exceptione)
{

     log.error(e.getMessage(), e);

       return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);

     

   }


}

5 测试image.png

目录
相关文章
|
3月前
|
安全 Java 程序员
代码救火队:try-catch-finally带你走出异常困境
代码救火队:try-catch-finally带你走出异常困境
36 0
|
JSON 缓存 安全
满屏的try-catch,你不瘆得慌?
满屏的try-catch,你不瘆得慌?
因为一道题,我把 try-catch-finally 的细节都整理了一遍(1500字)
原因:return i++; 在内部是可以分为三步,① int tmp = i; ② i += 1; ③ return tmp;
82 0
因为一道题,我把 try-catch-finally 的细节都整理了一遍(1500字)
一个try-catch问出这么多花样【面试题】
一个try-catch问出这么多花样【面试题】
83 0
一个try-catch问出这么多花样【面试题】
|
存储 Oracle Java
try-catch-finally中的4个巨坑,老程序员也搞不定!
在 Java 语言中 try-catch-finally 看似简单,一副人畜无害的样子,但想要真正的“掌控”它,却并不是一件容易的事。别的不说,咱就拿 fianlly 来说吧,别看它的功能单一,但使用起来却“暗藏杀机”,若您不信,咱来看下面的这几个例子...
191 0
try-catch-finally中的4个巨坑,老程序员也搞不定!
|
程序员
try-catch-finally中的4个巨坑,老程序员也搞不定!(2)
try-catch-finally中的4个巨坑,老程序员也搞不定!(2)
129 0
try-catch-finally中的4个巨坑,老程序员也搞不定!(2)
|
Java 程序员
try-catch-finally中的4个巨坑,老程序员也搞不定!(1)
try-catch-finally中的4个巨坑,老程序员也搞不定!(1)
119 0
try-catch-finally中的4个巨坑,老程序员也搞不定!(1)
|
程序员
try-catch-finally中的4个巨坑,老程序员也搞不定!(5)
try-catch-finally中的4个巨坑,老程序员也搞不定!(5)
90 0
try-catch-finally中的4个巨坑,老程序员也搞不定!(5)
|
Java 程序员
try-catch-finally中的4个巨坑,老程序员也搞不定!(4)
try-catch-finally中的4个巨坑,老程序员也搞不定!(4)
100 0
try-catch-finally中的4个巨坑,老程序员也搞不定!(4)
|
存储 Oracle 关系型数据库
try-catch-finally中的4个巨坑,老程序员也搞不定!(3)
try-catch-finally中的4个巨坑,老程序员也搞不定!(3)
115 0
try-catch-finally中的4个巨坑,老程序员也搞不定!(3)