SpringBoot对异常的统一处理

135 篇文章 0 订阅
16 篇文章 0 订阅

业务场景

统一处理try-catch的异常,并记录日志

代码

BaseBigRuntimeException

import com.alibaba.fastjson.JSON;
import com.watsons.onstore.common.vo.RestResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * 运行时异常封装类
 */
public class BaseBigRuntimeException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    protected static Map<String, String> mapMessage = new HashMap();
    public static final String SYSTEM_INTERNAL_ERROR = "10001";
    public static final String PARAMETER_ERROR = "10002";
    public static final String RECORD_DUPLICATED = "11001";
    public static final String RECORD_NOTEXIST = "11002";
    public static final String APIGATEWAY_ERROR = "99999";
    protected String code;
    protected String rawMessage;

    public BaseBigRuntimeException(String message) {
        this("10001", message);
    }

    public BaseBigRuntimeException(String message, Throwable e) {
        this("10001", message, e);
    }

    public BaseBigRuntimeException(String code, String message) {
        super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\"}");
        this.code = null;
        this.rawMessage = null;
        this.code = code;
        this.rawMessage = message;
    }

    public BaseBigRuntimeException(String code, String message, Throwable e) {
        super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\"}", e);
        this.code = null;
        this.rawMessage = null;
        this.code = code;
        this.rawMessage = message;
    }

    public String getCode() {
        return this.code;
    }

    public String getRawMessage() {
        return this.rawMessage;
    }

    public String toRestResponseJson() {
        return JSON.toJSONString(new RestResponse(this.code, this.rawMessage));
    }

    public static String getMessage(int code) {
        return (String)mapMessage.get(code);
    }

    static {
        mapMessage.put("10001", "系统内部错误");
        mapMessage.put("10002", "业务参数异常");
        mapMessage.put("11001", "记录重复");
        mapMessage.put("11002", "记录不存在");
    }
}

BigException

/**
 * 业务异常封装
 */
public class BigException extends BaseBigRuntimeException {

    public BigException(String info) {
        super(ExceptionCode.FAIL.getCode(), info);
    }

    public BigException(String code, String info) {
        super(code, info);
    }
}

ExceptionCode

/**
 * 异常错误编码
 */
public enum ExceptionCode {
	/**
	 * 异常错误编码
	 *
	 * */
	SYSTEM_ERROR("000000", "系统异常" +
			""),
	SUCCESS("0", "操作成功"),
	FAIL("100000", "操作失败"),
//	NOT_SUPPORTED("100001", "渠道不支持该接口"),
	INVOKE("-2", "接口调用失败"),
	VALIDATION_FAIL("1000", "数据验证失败"),
	INVALID_PARAM("2000", "参数不合法"),
	PARAM_EMPTY_ERROR("2001", "参数不能为空"),
	RECORD_NOT_EXIST("3000", "记录不存在"),
	AUTH_ERROR("4008", "缺失参数auth");

	private final String code;
	private final String msg;

	ExceptionCode(String val, String info) {
		this.code = val;
		this.msg = info;
	}

	public void throwBizException() {
		throw new BigException(this.getCode(), this.getMsg());
	}

	public String getCode() {
		return this.code;
	}

	public String getMsg() {
		return this.msg;
	}


}

BaseControllerAdvice(捕获异常类)
记得在启动类上的@ComponentScan,扫描BaseControllerAdvice

import com.watsons.onstore.common.exception.BigException;
import com.watsons.onstore.common.exception.ExceptionCode;
import com.watsons.onstore.common.vo.RestResponse;
import com.watsons.onstore.framework.logs.OsLog;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class BaseControllerAdvice {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    RestResponse handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return new RestResponse(ExceptionCode.SYSTEM_ERROR.getCode(), ExceptionCode.SYSTEM_ERROR.getMsg());
    }

    @ExceptionHandler(BigException.class)
    RestResponse handleBusinessException(BigException e) {
        logger.error(e.getMessage(), e);
        return new RestResponse(e.getCode(), e.getRawMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    RestResponse handleException(MethodArgumentNotValidException e) {
        StringBuffer sb = new StringBuffer();
        List<FieldError> fieldErrorList = e.getBindingResult().getFieldErrors();
        if (CollectionUtils.isNotEmpty(fieldErrorList)) {
            boolean isFirst = true;
            for (FieldError error : fieldErrorList) {
                if (isFirst) {
                    isFirst = false;
                }else {
                    sb.append(";");
                }
                sb.append(error.getDefaultMessage());
            }
        }
        String errorMsg = sb.toString();
        logger.error(errorMsg, e);
        return new RestResponse(ExceptionCode.VALIDATION_FAIL.getCode(), errorMsg);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值