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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章