1. 程式人生 > >spring boot中全域性異常的定義

spring boot中全域性異常的定義

全域性異常

import com.alibaba.fastjson.JSON;
import com.ziku.msp.common_enum.ErrorCodeEnum;
import com.ziku.msp.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageNotReadableException;
import 
org.springframework.stereotype.Component; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import
org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.io.IOException; import java.util.HashMap; import
java.util.Map; import java.util.stream.Collectors; @Slf4j @Component public class GlobalExceptionHandler implements HandlerExceptionResolver, Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; @Override public int getOrder() { return 0; } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) { Map<String, Object> map = new HashMap<String, Object>(); if (ex instanceof BizException) { log.info("GlobalExceptionHandler>>>>>異常資訊:{}", ExceptionUtils.getStackTrace(ex)); BizException runtimeException = (BizException) ex; map.put("errorCode", runtimeException.getErrorCode()); map.put("errorMsg", runtimeException.getErrorMsg()); }else if (ex instanceof HttpRequestMethodNotSupportedException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUEST_METHOD_ERROR.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUEST_METHOD_ERROR.getErrorMsg()); }else if (ex instanceof NoHandlerFoundException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUESTED_URL_DOESNT_EXIST.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUESTED_URL_DOESNT_EXIST.getErrorMsg()); } else if (ex instanceof ServletRequestBindingException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorMsg()); } else if (ex instanceof HttpMessageNotReadableException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorMsg()); }else if (ex instanceof ConstraintViolationException) { log.error("-------controller exception-------", ex); final String msg = ((ConstraintViolationException) ex).getConstraintViolations().stream() .map(ConstraintViolation::getMessage) .collect(Collectors.joining(",")); map.put("errorCode", "400"); map.put("errorMsg", msg); } else { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.INTERNAL_SERVER_ERROR.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.INTERNAL_SERVER_ERROR.getErrorMsg()); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8"); String method = request.getMethod(); String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Credentials", "true"); //response.setHeader("Access-Control-Allow-Origin", "*");//解決跨域問題 response.setHeader("Access-Control-Allow-Headers", "*"); // 特殊的header需要定義,Content-Type等常用請求頭不需要設定加入 response.setHeader("Access-Control-Allow-Methods","*"); response.setStatus(200); try { response.getWriter().print(JSON.toJSONString(map)); } catch (IOException e) { e.printStackTrace(); } return new ModelAndView(); } }
執行時異常的統一封裝
public class BizException extends RuntimeException {
    /**
     *
     */
private static final long serialVersionUID = -5110371239340231002L;

    private String errorCode;

    private String errorMsg;

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

    public BizException(String message) {
        super(message);
    }

    public BizException(String message, Throwable cause) {
        super(message, cause);
    }

    public BizException(Exception exception) {
        super(exception);
    }

    public BizException(ErrorCodeEnum errorCode, Throwable cause) {
        super(cause);
        this.errorCode = errorCode.getErrorCode();
        this.errorMsg = errorCode.getErrorMsg();
    }

    public BizException(String errorCode, String errorMsg) {
        super();
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public BizException(ErrorCodeEnum errorCode) {
        super();
        this.errorCode = errorCode.getErrorCode();
        this.errorMsg = errorCode.getErrorMsg();
    }

    public String getErrorCode() {
        return errorCode;
    }

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

    public String getErrorMsg() {
        return errorMsg;
    }

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

定義異常列舉

public enum ErrorCodeEnum {
    REQUEST_METHOD_ERROR("-3", "介面請求方法型別錯誤"),

    REQUEST_PARAMETER_IS_INCORRECT("-2", "請求引數有誤"),

    INTERNAL_SERVER_ERROR("-1", "服務繁忙"),

    REQUESTED_URL_DOESNT_EXIST("-4", "請求的資源不存在"),

    OPERATION_FREQUENTLY("-5", "請求頻繁,請勿重複請求"),

    REQUEST_COUNT_LIMIT("10000", "訪問次數超出限制"),

    SUCCESS("0", "請求成功"),

    MISSING_SYSTEM_PARAMETERS("6", "缺少系統引數"),

    APP_KEY_NOT_EXIST("7", "app_key不存在或合作方不合作"),

    API_VERSION_NOT_SUPPORT("8", "api版本號不支援"),

    PARAM_SIGN_FAILED("9", "引數驗證失敗");




    private ErrorCodeEnum(String errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    private String errorCode;
    private String errorMsg;

    public String getErrorCode() {
        return errorCode;
    }

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

    public String getErrorMsg() {
        return errorMsg;
    }

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