Java 封装全局异常类

今天学习Java第五天,写demo的时候捕获异常,很不习惯,毕竟PHP可以很方便直观的处理,查查资料,自己写了一个,刚开始学,写的有点LOW

1.全局异常处理类

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cg.xcx.common.base.JsonReturn;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
    private Environment environment;
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonReturn  defaultErrorHandler(HttpServletRequest request, Exception ex)
            throws Exception {
        String errorCode = null;
        String errorMsg = null;
        Object errorData = new ArrayList();
        String active = environment.getProperty("spring.profiles.active");
        if (ex instanceof BusinessException) {
            BusinessException se = (BusinessException) ex;
            errorCode = se.getCode();
            errorMsg = se.getMessage();
            errorData = se.getData();
            // 屏蔽线上异常
        } else if(active == "prod"){
            errorCode = "0";
            errorMsg = "内部服务错误";
        } else {
            ex.printStackTrace();
        }
         return  new JsonReturn(errorCode,errorMsg, errorData);
    }


}

2.创建一个异常文件  exception

定义一个继承runtime异常的类,BaseRuntimeException

import org.springframework.util.StringUtils;

import java.util.List;


public class BaseRuntimeException extends RuntimeException  {
    private Object errorData;
    private Throwable cause = null;
    private String errorCode = null;

    private String errorMsg = ""; // 客户描述
    private String alarmMsg = "!@#$"; // 告警描述

    static final long serialVersionUID = 0L;

    public BaseRuntimeException() {
    }

    public BaseRuntimeException(String errorCode) {
        this.errorCode = errorCode;
    }

    /**
     * 透传其他模块的错误信息 Creates a new instance of BaseRuntimeException.
     *
     * @param errorCode
     * @param msg
     */
    public BaseRuntimeException(String errorCode, String msg) {
        super(msg);
        this.errorMsg = msg;
        this.errorCode = errorCode;
        System.out.println(this.errorCode);
        System.out.println(this.errorMsg);
    }

    /**
     * 透传其他模块的错误信息并告警 Creates a new instance of BaseRuntimeException.
     *
     * @param errorCode
     * @param msg
     */
    public BaseRuntimeException(String errorCode, String msg, String alarmMsg) {
        super(msg);
        this.errorMsg = msg;
        this.alarmMsg = alarmMsg;
        this.errorCode = errorCode;
    }

    public BaseRuntimeException(Throwable cause) {
        super(cause);
    }

    public BaseRuntimeException(String errorCode, String msg, Throwable cause) {
        super(msg);
        this.cause = cause;
        this.errorCode = errorCode;
    }
    public BaseRuntimeException(String errorCode, String msg, Object data) {
        super(msg);
        this.errorData = data;
        this.errorCode = errorCode;
    }

    @Override
    public Throwable getCause() {
        return this.cause;
    }

    public String getExceptionMessage() {
        if (super.getMessage() != null) {
            return super.getMessage();
        }
        if (this.cause != null) {
            return this.cause.toString();
        }
        return null;
    }


    public String getErrorCode() {
        return this.errorCode;
    }

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

    public String getErrorMsg() {
        return errorMsg;
    }

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

    public String getAlarmMsg() {
        return alarmMsg;
    }

    public void setAlarmMsg(String alarmMsg) {
        this.alarmMsg = alarmMsg;
    }

    public boolean isAlarm() {
        if ((!StringUtils.isEmpty(this.alarmMsg)) && (!this.alarmMsg.equals("!@#$"))) {
            return true;
        }
        return false;
    }

}
 

3.定义全局返回

import java.util.ArrayList;

/**
 * 全局错误码
 * Created by LY on 2018/04/11.
 */
public enum GlobalErrorCode{
    // Login error

    LOGIN_ERROR_TOKEN_INVALID("-10000", "无效的token.", new ArrayList<>()),
    /**
     * 参数类错误码
     */
    REQUEST_PACKET_ERROR("400010","请求数据错误!"),
    TCP_SYSTEM_CONNECT_ERROR("400012","连接数据服务器失败!"),
    REQUEST_PARSE_PACKET_ERROR("400015","服务器处理数据失败!"),

    REQUEST_DB_ADD_ERROR("30001","数据库添加处理失败!"),

    REQUEST_DB_SAVE_ERROR("30002","数据库修改处理失败!"),

    REQ_PARAM_TOKEN_NOTNULL("400014","token参数为空!"),

    REQ_PARAM_TTL_INVALID("-10000","登陆超时!");

    GlobalErrorCode(String code,String message){
        this.code = code;
        this.message = message;
    }
    GlobalErrorCode(String code,String message, Object data){
        this.code = code;
        this.message = message;
        this.data = data;
    }

    private String code;
    private String message;
    private Object data;


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


    public String getMessage() {
        return this.message;
    }


    public Object getData() {
        return data;
    }

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

4.错误捕捉

import java.util.List;

public class BusinessException extends BaseRuntimeException {

    private static final long serialVersionUID = 1L;

    //自定义错误码
    private String code;
    private Object data;

    //自定义构造器,只保留一个,让其必须输入错误码及内容
    public BusinessException(String code, String msg) {
        super(code, msg);
        this.code = code;
    }

    public BusinessException(String code, String msg, Object data) {
        super(code, msg, data);
        this.code = code;
        this.data = data;
    }

    public BusinessException(GlobalErrorCode globalErrorCode) {
        super(globalErrorCode.getCode(), globalErrorCode.getMessage(), globalErrorCode.getData());
        this.code = globalErrorCode.getCode();
        this.data = globalErrorCode.getData();
    }


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

    public void setCode(String code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

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

基本以上四个可以拿去直接使用

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值