基于Spring AOP如何实现通用异常拦截器 - Go语言中文社区

基于Spring AOP如何实现通用异常拦截器


通常呢在项目里,我们会用大catch包住异常,但是这么做在生产上将影响问题定位;为了在项目中更规范的进行编码,本文将详细介绍如何基于AOP来实现异常拦截
处理结果:

404请求异常
在这里插入图片描述
请求参数异常
在这里插入图片描述

一、开启AspectJ的Proxy设置,使得SpringBoot容器可以解析aop配置

@EnableAspectJAutoProxy(proxyTargetClass = true)
在这里插入图片描述

二、定义通用返回逻辑

2.1 通用返回类 CommonRes.class

package com.yfy.dianping.common;

/**
 * @author youfy
 */
public class CommonRes {
    /**
     *请求的返回处理结果,"success"或"fail"
     */
    private String status;
    /**
     * 若status=success时,表明对应的返回的json类数据
     * 若status=fail时,则data内将使用通用的错误码对应的格式
     */
    private Object data;
    /**
     *定义一个通用的创建返回对象的方法
     */
    public static CommonRes create(Object result){
        return CommonRes.create(result,"success");
    }

    public static CommonRes create(Object result,String status){
        CommonRes commonRes = new CommonRes();
        commonRes.setStatus(status);
        commonRes.setData(result);
        return commonRes;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

2.2 通用异常类 CommonError.class

package com.yfy.dianping.common;

/**
 * @author youfy
 */
public class CommonError {
    /**
     * 错误码
     */
    private Integer errCode;
    /**
     * 错误描述
     */
    private String errMsg;

    public CommonError(Integer errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public CommonError(EmBusinessError emBusinessError){
        this.errCode = emBusinessError.getErrCode();
        this.errMsg = emBusinessError.getErrMsg();
    }
    public Integer getErrCode() {
        return errCode;
    }

    public void setErrCode(Integer errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }
}

2.3业务异常 BusinessException.class

package com.yfy.dianping.common;

/**
 * @author youfy
 */
public class BusinessException extends Exception {
    private CommonError commonError;

    public BusinessException(EmBusinessError emBusinessError){
        super();
        this.commonError = new CommonError(emBusinessError);
    }

    public CommonError getCommonError() {
        return commonError;
    }

    public void setCommonError(CommonError commonError) {
        this.commonError = commonError;
    }
}

2.4 异常枚举 EmBusinessError.class

package com.yfy.dianping.common;

/**
 * @author youfy
 */

public enum EmBusinessError {
    //通用的错误类型以10000开头
    NO_OBJECT_FOUND(10001, "请求对象不存在"),
    UNKNOWN_ERROR(10002, "未知异常"),
    NO_HANDLE_FOUND(10003, "找不到执行的路径操作"),
    BIND_EXCEPTION_ERROR(10004, "请求参数错误"),

    ;

    private Integer errCode;

    private String errMsg;

    EmBusinessError(Integer errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public Integer getErrCode() {
        return errCode;
    }

    public void setErrCode(Integer errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }
}

三、定义全局异常处理器,使用@ControllerAdvice可覆盖所有controller

全局异常处理器 GlobalExceptionHandler.class

package com.yfy.dianping.common;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author youfy
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
public CommonRes doError(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
                         Exception ex) {
  	  if (ex instanceof BusinessException) {
            return CommonRes.create(((BusinessException) ex).getCommonError(), "fail");
        } else if (ex instanceof NoHandlerFoundException) {
            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLE_FOUND);
            return CommonRes.create(commonError, "fail");
        } else if (ex instanceof ServletRequestBindingException) {
            CommonError commonError = new CommonError(EmBusinessError.BIND_EXCEPTION_ERROR);
            return CommonRes.create(commonError, "fail");
        } else {
            CommonError commonError = new CommonError(EmBusinessError.UNKNOWN_ERROR);
            return CommonRes.create(commonError, "fail");
        }
    }
}

四、处理404请求异常,设置:拒绝404默认的处理,如果没找到处理器就抛出异常

application.properties下配置:

spring.resources.add-mappings=true
spring.mvc.throw-exception-if-no-handler-found=true

五、处理请求参数异常,用ServletRequestBindingException捕获

if (ex instanceof NoHandlerFoundException) {
	            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLE_FOUND);
	            return CommonRes.create(commonError, "fail");
 } 
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/loulanyue_/article/details/90705709
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢