spring異常處理@ControllerAdvice

1.自定義異常

package com.xxx.finance.common.exception;

/**
 * 異常抽象類
 * Created by xdc on 2016/8/3 14:36.
 */
public abstract class FinanceException extends RuntimeException {

    private ExceptionGrade grade = ExceptionGrade.UNSERIOUS;
    private Integer exceptionCode = 0;
    private Throwable cause = null;
    private String message = null;

    public FinanceException() {
        super();
    }

    protected FinanceException(Integer exceptionCode, ExceptionGrade exceptionGrade, String message) {
        if (exceptionGrade != null) {
            this.grade = exceptionGrade;
        }
        if (exceptionCode != null) {
            this.exceptionCode = exceptionCode;
        }
        this.message = "excpStart" + message + "excpEnd";
    }

    protected FinanceException(ExceptionGrade exceptionGrade, String message) {
        if (exceptionGrade != null) {
            this.grade = exceptionGrade;
        }
        this.message = message;
    }


    protected FinanceException(ExceptionGrade exceptionGrade) {
        if (exceptionGrade != null) {
            this.grade = exceptionGrade;
        }
    }

    protected FinanceException(String message) {
        this.message = message;
    }

    public ExceptionGrade getGrade() {
        return grade;
    }

    public void setGrade(ExceptionGrade grade) {
        this.grade = grade;
    }

    public Throwable getCause() {
        return cause;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }

    public Integer getExceptionCode() {
        return exceptionCode;
    }

    public void setExceptionCode(Integer exceptionCode) {
        this.exceptionCode = exceptionCode;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

package com.xxx.finance.common.exception;

/**
 * 財務異常
 * Created by xdc on 2016/8/3 14:37.
 */
public class FinanceExceptionService extends FinanceException {


    public FinanceExceptionService() {
        super();
    }

    public FinanceExceptionService(String exceptionCode) {
        super(Integer.valueOf(exceptionCode), null, null);
    }

    /**
     * 修改返回消息
     * @param exceptionCode 異常代碼
     * @param message       異常消息
     */
    public FinanceExceptionService(String exceptionCode, String message) {
        super(Integer.valueOf(exceptionCode), null, "excpStart" + message + "excpEnd");
    }

    public FinanceExceptionService(ExceptionGrade exceptionGrade, String message) {
        super(exceptionGrade, message);
    }

    public FinanceExceptionService(Integer exceptionCode, ExceptionGrade exceptionGrade, String message) {
        super(exceptionCode, exceptionGrade, message);
    }

    public FinanceExceptionService(String exceptionCode, ExceptionGrade exceptionGrade) {
        super(Integer.valueOf(exceptionCode), exceptionGrade, null);
    }
}

2.返回值基類

package com.xxx.finance.common.model;

import org.apache.commons.lang.builder.*;

/**
 * Created by xdc on 2016/8/3 15:32.
 */
public class ResponseHeaderModel {

    protected long time=System.currentTimeMillis();
    protected String message="SUCCESS";
    protected Integer code = 0;

    public ResponseHeaderModel() {
        super();
    }

    public ResponseHeaderModel(long time,String message, Integer code) {
        this.time=time;
        this.message = message;
        this.code = code;
    }

    public long getTime() {
        return time;
    }

    public String getMessage() {
        return message;
    }

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

package com.xxx.finance.common.model;

import com.xxx.finance.common.exception.*;
import net.sf.json.*;

/**
 * Created by xdc on 2016/8/3 15:32.
 */
public class ResponseModel extends ResponseHeaderModel {
    private Object data;

    public ResponseModel() {
        super();
        super.time = System.currentTimeMillis();
    }

    public ResponseModel(Object data) {
        this.data = data;
        super.time = System.currentTimeMillis();

    }

    public ResponseModel(int code, String massage) {
        super.code = code;
        super.message = massage;
        super.time = System.currentTimeMillis();
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
        super.time = System.currentTimeMillis();
    }

    public static ResponseModel successResult() {
        ResponseModel ro = new ResponseModel();
        ro.setCode(ResultCode.codeSuccess);
        ro.setMessage(ResultCode.massageSuccess);
        return ro;
    }

    public static ResponseModel errorResult() {
        ResponseModel ro = new ResponseModel();
        ro.setCode(ResultCode.codeError);
        ro.setMessage(ResultCode.massageError);
        return ro;
    }

    @Override
    public String toString() {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("message", message);
        jsonObject.put("data", data);

        return jsonObject.toString();
    }
}

3.異常攔截類

package com.xxx.finance.interceptor;

import com.xxx.finance.common.exception.*;
import com.xxx.finance.common.model.*;
import org.springframework.web.bind.annotation.*;

/**
 * 異常攔截類
 * Created by xdc on 2016/8/3 15:25.
 */
@ControllerAdvice
public class ExceptionHandler {

    @ResponseBody
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public ResponseModel handleUnexpectedServerError(Exception ex) {
        ex.printStackTrace();

        // 處理異常
        ResponseModel response = new ResponseModel();

        String errorMsg = ex.getMessage();
        response.setCode(Integer.valueOf(ResultCode.SYSTEM_EXCEPTION));
        if(errorMsg.contains("excpStart")){
            errorMsg = errorMsg.substring(errorMsg.indexOf("excpStart") + 9, errorMsg.indexOf("excpEnd"));
        }
        response.setMessage(errorMsg);

        // 返回數據
        return response;
    }

}

4.前端獲取異常

if(confirm("確認作廢?")){
            $.ajax({
                type : "POST",
                url : "../invoice/cancelInvoice?ran="+Math.random(),
                data : {
                    id : id,
                    timestamp : lastChangedDate
                },
                cache : false,
                async : true,
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    $.globalMessenger().post({
                        message : "系統異常,請聯繫管理員!",
                        type : "error"
                    });
                },
                success : function(res) {
                    if (res && res.code == 0) {
                        showMsg("發票作廢成功");
                    }else{
                        showMsg(res.message, "error");
                    }
                }
            });
        }

5.異常測試

throw new FinanceExceptionService("3", "異常測試");










(另一個項目異常處理備份)

1.自定義異常

package com.xx.cloud.assets.common.exception;

import org.slf4j.*;

import com.xx.cloud.assets.common.constant.ResponseCode;

/**
 * xx管理exception
 */
public class AssetException extends Exception {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private Integer exceptionCode = 0;
    private String message = null;

   
    private static final long serialVersionUID = 1L;

    public AssetException() {
        super();
    }

    public AssetException(Integer exceptionCode, String message) {
        if (exceptionCode != null) {
            this.exceptionCode = exceptionCode;
        }
        this.message = message;
    }

    public AssetException(ResponseCode responseCode) {
        this.exceptionCode = responseCode.getCode();
        this.message = responseCode.getMessage();
    }


    public AssetException(String message) {
        this.message = message;
    }

    public Integer getExceptionCode() {
        return exceptionCode;
    }

    public void setExceptionCode(Integer exceptionCode) {
        this.exceptionCode = exceptionCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

2.異常代碼

package com.xx.cloud.assets.common.constant;


public enum ResponseCode {



    /**
     * 操作成功!
     */
    SUCCESS(0, "操作成功!"),

    UNKONW_ERROR(-1,"未知錯誤!"),
    /**
     * 操作失敗!
     */
    ERROR(1, "操作失敗!"),

    /**
     * 登錄失敗
     */
    LOGIN_ERROR(2, "賬號或密碼錯誤,請重新輸入!"),

    /**
     * 登出失敗!
     */
    LOGOUT_ERROR(3, "登出失敗!"),

    NO_READ_PERMISSION(59001,"該資產非本公司資產,無權限查看!"),

    NO_WRITE_PERMISSION(59003,"無權操作!"),

    PARAM_ERROR(59002,"參數錯誤"),
    UNAUTHENTICATION(50003, "認證失敗,請重新登錄"),

    UNAUTHORIZATION(60001, "權限驗證失敗,請聯繫管理員");

    /** 返回狀態code */
    private Integer code = 0;

    /** 狀態描述 */
    private String message = null;

    private ResponseCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public static ResponseCode fromValue(Integer code) {
        for (ResponseCode field : values()) {
            if (field.code == code) {
                return field;
            }
        }
        return null;
    }
}

3.異常攔截

package com.xx.cloud.assets.web.exceptionHandler;

import java.util.HashMap;

import javax.annotation.Resource;

import com.xx.cloud.assets.common.constant.Constant;
import com.xx.cloud.assets.common.constant.ResponseCode;
import com.xx.cloud.assets.common.exception.AssetException;
import com.xx.cloud.assets.common.response.AssetResponse;
import com.xx.cloud.assets.service.authority.AssetAuthorityService;
import com.xx.shiro.exception.UnauthorizedException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class ControllerExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @Resource(name = "assetAuthorityService")
    private AssetAuthorityService assetAuthorityService;

    /**
     * 處理未期望的服務異常
     * @param throwable 拋出異常
     * @return 接口應答
     */
    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public AssetResponse<String> handleUnexpectedServerError(Throwable throwable) {
        throwable.printStackTrace();
      
        // 處理異常
        AssetResponse<String> response = new AssetResponse<String>();
        if (throwable instanceof AssetException) {
            AssetException exception = (AssetException) throwable;
            response.setCode(exception.getExceptionCode());
            response.setMessage(exception.getMessage());
        } else if (throwable instanceof UnauthenticatedException) {
            response.setResponseCode(ResponseCode.UNAUTHENTICATION);
        } else if (throwable instanceof UnauthorizedException) {
            UnauthorizedException exception = (UnauthorizedException) throwable;
            response.setCode(ResponseCode.UNAUTHORIZATION.getCode());
            HashMap<String, String> data = exception.getData();
            String permissionCode = data.get(Constant.PERMISSIONS);
            String role = data.get(Constant.ROLES);
            if (StringUtils.isNotBlank(permissionCode)) {
                String permissionName = assetAuthorityService.getPermissionNameByCode(permissionCode);
                response.setMessage(String.format("您暫無%s的權限,請聯繫管理員。", permissionName).toString());
            }
            if (StringUtils.isNotBlank(role)) {
                response.setMessage(String.format("您暫無%s的角色,請聯繫管理員。", role).toString());
            }
            if (StringUtils.isBlank(permissionCode) && StringUtils.isBlank(role)) {
                response.setResponseCode(ResponseCode.UNAUTHORIZATION);
            }
        } else {
            response.setResponseCode(ResponseCode.UNKONW_ERROR);
        }

        logger.error("handle Uncatch Exception", throwable);

        // 返回數據
        return response;
    }
}


注:該類需要被掃描到




發佈了107 篇原創文章 · 獲贊 61 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章