Abnormal interceptor how Spring AOP-based implementation of general

It is usually in the project, we will wrap with a big catch exceptions, but doing so will locate in the production of impact; To encode more standardized in the project, this article will detail how to implement exception-based AOP intercept
processing results:

404 Request exception
Here Insert Picture Description
request parameter error
Here Insert Picture Description

First, the opening AspectJ Proxy settings, such containers can be resolved aop configuration SpringBoot

@EnableAspectJAutoProxy(proxyTargetClass = true)
Here Insert Picture Description

Second, define a common return logic

2.1 General Returns the class 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 General exception class 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 Business abnormal 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 abnormal enumeration 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;
    }
}

Third, define a global exception handler, using the controller covers all @ControllerAdvice

Global exception handler 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");
        }
    }
}

Fourth, the process 404 requests an exception, set: refuse default processing 404, if the processor did not find throws an exception

application.properties Configuration:

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

Fifth, the exception processing request parameters, captured by ServletRequestBindingException

if (ex instanceof NoHandlerFoundException) {
	            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLE_FOUND);
	            return CommonRes.create(commonError, "fail");
 } 
Published 132 original articles · won praise 52 · views 70000 +

Guess you like

Origin blog.csdn.net/loulanyue_/article/details/90705709