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

程序新视界

共 6217字,需浏览 13分钟

 ·

2021-03-23 21:26

来源:www.toutiao.com/i6878184496945070604

前言

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

  • 可以灵活的根据自己的业务异常进行更细粒度的扩展

实践

1 封装统一返回结果类

实现代码:
public class AjaxResult {
 //是否成功
    private Boolean success;
    //状态码
    private Integer code;
    //提示信息
    private String msg;
    //数据
    private Object data;
    public AjaxResult() {

    }
    //自定义返回结果的构造方法
    public AjaxResult(Boolean success,Integer code, String msg,Object data) {
        this.success = success;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    //自定义异常返回的结果
    public static AjaxResult defineError(BusinessException de){
     AjaxResult result = new AjaxResult();
        result.setSuccess(false);
        result.setCode(de.getErrorCode());
        result.setMsg(de.getErrorMsg());
        result.setData(null);
        return result;
    }
    //其他异常处理方法返回的结果
    public static 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 自定义异常封装类

实现源码:
public class BusinessException extends RuntimeException {
 private static final long serialVersionUID = 1L;
 /**
  * 错误状态码
  */

 protected Integer errorCode;
 /**
  * 错误提示
  */

 protected String errorMsg;

 public BusinessException(){}

 public BusinessException(Integer errorCode, String errorMsg) {
         this.errorCode = errorCode;
         this.errorMsg = errorMsg;
     }

 public Integer getErrorCode() {
  return errorCode;
 }

 public void setErrorCode(Integer errorCode) {
  this.errorCode = errorCode;
 }

 public String getErrorMsg() {
  return errorMsg;
 }

 public void setErrorMsg(String errorMsg) {
  this.errorMsg = errorMsg;
 }
}

3 错误枚举,拒绝硬编码

public enum 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
public class GlobalExceptionHandler{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

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

    @ExceptionHandler(value = BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e
{
     log.error(e.getMessage(), e);
        return AjaxResult.defineError(e);
    }

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

    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandlerException e
{
      log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
       
    }

}

5 测试

返回结果:

往期推荐

SpringBoot接口幂等性实现的4种方案!

面试题:将字符串反转的8种方法,你能想到几种?

面试题:重写equals方法为什么通常会重写hashcode方法?

为什么是反向代理,什么又是正向代理?

5张图,带你了解微服务架构治理




如果你觉得这篇文章不错,那么,下篇通常会更好。添加微信好友,可备注“加群”(微信号:zhuan2quan)

一篇文章就看透技术本质的人,
  和花一辈子都看不清的人,
  注定是截然不同的搬砖生涯。
▲ 按关注”程序新视界“,洞察技术内幕
浏览 41
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报