1. 程式人生 > >Springboot-系統異常統一處理(介面程式設計異常處理)

Springboot-系統異常統一處理(介面程式設計異常處理)

Springboot-系統異常統一處理(介面程式設計異常)

1. 系統異常捕獲

/**
 * 全域性異常處理
 * @Author: wangxc
 * @GitHub: https://github.com/vector4wang
 * @CSDN: http://blog.csdn.net/qqhjqs?viewmode=contents
 * @BLOG: http://vector4wang.tk
 * @wxid: BMHJQS
 * 參考:http://neverflyaway.iteye.com/blog/2301571  http://blog.csdn.net/u010935920/article/details/71024018
 */
@ControllerAdvice(annotations = {RestController.class}) public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 系統異常處理,比如:404,500 * @param req * @param e * @return * @throws Exception */ @ExceptionHandler
(value = Exception.class) @ResponseBody public BaseResp<?> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { logger.error("", e); BaseResp baseResp = new BaseResp(); baseResp.setMessage(e.getMessage()); if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) { baseResp.setCode(ResultStatus.http_status_not_found.getErrorCode()); } else
{ baseResp.setCode(ResultStatus.http_status_internal_server_error.getErrorCode()); } baseResp.setData(""); return baseResp; } }

2. 資料返回統一格式

import java.util.Date;

/**
 * @param <T>
 */
public class BaseResp<T> {
    /**
     * 返回碼
     */
    private int code;

    /**
     * 返回資訊描述
     */
    private String message;

    /**
     * 返回資料
     */
    private T data;

    private long currentTime;

    public int getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

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

    public Object getData() {
        return data;
    }

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

    public long getCurrentTime() {
        return currentTime;
    }

    public void setCurrentTime(long currentTime) {
        this.currentTime = currentTime;
    }

    public BaseResp(){}

    /**
     *
     * @param code 錯誤碼
     * @param message 資訊
     * @param data 資料
     */
    public BaseResp(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.currentTime = System.currentTimeMillis();
    }

    /**
     * 不帶資料的返回結果
     * @param resultStatus
     */
    public BaseResp(ResultStatus resultStatus) {
        this.code = resultStatus.getErrorCode();
        this.message = resultStatus.getErrorMsg();
        this.data = data;
        this.currentTime = System.currentTimeMillis();
    }

    /**
     * 帶資料的返回結果
     * @param resultStatus
     * @param data
     */
    public BaseResp(ResultStatus resultStatus, T data) {
        this.code = resultStatus.getErrorCode();
        this.message = resultStatus.getErrorMsg();
        this.data = data;
        this.currentTime = System.currentTimeMillis();
    }

}

3. 錯誤碼

public enum ResultStatus {

    // -1為通用失敗(根據ApiResult.java中的構造方法註釋而來)
    FAIL(-1, "common fail"),
    // 0為成功
    SUCCESS(0, "success"),

    error_pic_file(3,"非法圖片檔案"),
    error_pic_upload(4,"圖片上傳失敗"),
    error_record_not_found(5, "沒有找到對應的資料"),
    error_max_page_size(6, "請求記錄數超出每次請求最大允許值"),
    error_create_failed(7,"新增失敗"),
    error_update_failed(8,"修改失敗"),
    error_delete_failed(9,"刪除失敗"),
    error_search_failed(10,"查詢失敗"),
    error_count_failed(11,"查詢資料總數失敗"),
    error_string_to_obj(12,"字串轉java物件失敗"),
    error_invalid_argument(13,"引數不合法"),
    error_update_not_allowed(14,"更新失敗:%s"),
    error_duplicated_data(15,"資料已存在"),
    error_unknown_database_operation(16,"未知資料庫操作失敗,請聯絡管理員解決"),
    error_column_unique(17,"欄位s%違反唯一約束性條件"),
    error_file_download(18,"檔案下載失敗"),
    error_file_upload(19,"檔案上傳失敗"),

    //100-511為http 狀態碼
    // --- 4xx Client Error ---
    http_status_bad_request(400, "Bad Request"),
    http_status_unauthorized(401, "Unauthorized"),
    http_status_payment_required(402, "Payment Required"),
    http_status_forbidden(403, "Forbidden"),
    http_status_not_found(404, "Not Found"),
    http_status_method_not_allowed(405, "Method Not Allowed"),
    http_status_not_acceptable(406, "Not Acceptable"),
    http_status_proxy_authentication_required(407, "Proxy Authentication Required"),
    http_status_request_timeout(408, "Request Timeout"),
    http_status_conflict(409, "Conflict"),
    http_status_gone(410, "Gone"),
    http_status_length_required(411, "Length Required"),
    http_status_precondition_failed(412, "Precondition Failed"),
    http_status_payload_too_large(413, "Payload Too Large"),
    http_status_uri_too_long(414, "URI Too Long"),
    http_status_unsupported_media_type(415, "Unsupported Media Type"),
    http_status_requested_range_not_satisfiable(416, "Requested range not satisfiable"),
    http_status_expectation_failed(417, "Expectation Failed"),
    http_status_im_a_teapot(418, "I'm a teapot"),
    http_status_unprocessable_entity(422, "Unprocessable Entity"),
    http_status_locked(423, "Locked"),
    http_status_failed_dependency(424, "Failed Dependency"),
    http_status_upgrade_required(426, "Upgrade Required"),
    http_status_precondition_required(428, "Precondition Required"),
    http_status_too_many_requests(429, "Too Many Requests"),
    http_status_request_header_fields_too_large(431, "Request Header Fields Too Large"),

    // --- 5xx Server Error ---
    http_status_internal_server_error(500, "系統錯誤"),
    http_status_not_implemented(501, "Not Implemented"),
    http_status_bad_gateway(502, "Bad Gateway"),
    http_status_service_unavailable(503, "Service Unavailable"),
    http_status_gateway_timeout(504, "Gateway Timeout"),
    http_status_http_version_not_supported(505, "HTTP Version not supported"),
    http_status_variant_also_negotiates(506, "Variant Also Negotiates"),
    http_status_insufficient_storage(507, "Insufficient Storage"),
    http_status_loop_detected(508, "Loop Detected"),
    http_status_bandwidth_limit_exceeded(509, "Bandwidth Limit Exceeded"),
    http_status_not_extended(510, "Not Extended"),
    http_status_network_authentication_required(511, "Network Authentication Required"),

    // --- 8xx common error ---
    EXCEPTION(800, "exception"),
    INVALID_PARAM(801, "invalid.param"),
    INVALID_PRIVI(802, "invalid.privi"),

    //1000以內是系統錯誤,
    no_login(1000,"沒有登入"),
    config_error(1001,"引數配置表錯誤"),
    user_exist(1002,"使用者名稱已存在"),
    userpwd_not_exist(1003,"使用者名稱不存在或者密碼錯誤"),
    ;
    private static final Logger LOGGER =       LoggerFactory.getLogger(ResultStatus.class);

    private int code;
    private String msg;

    ResultStatus(int code, String msg){
        this.code = code;
        this.msg = msg;
    }

    public static int getCode(String define){
        try {
            return ResultStatus.valueOf(define).code;
        } catch (IllegalArgumentException e) {
            LOGGER.error("undefined error code: {}", define);
            return FAIL.getErrorCode();
        }
    }

    public static String getMsg(String define){
        try {
            return ResultStatus.valueOf(define).msg;
        } catch (IllegalArgumentException e) {
            LOGGER.error("undefined error code: {}", define);
            return FAIL.getErrorMsg();
        }
    }

    public static String getMsg(int code){
        for(ResultStatus err : ResultStatus.values()){
            if(err.code==code){
                return err.msg;
            }
        }
        return "errorCode not defined ";
    }

    public int getErrorCode(){
        return code;
    }

    public String getErrorMsg(){
        return msg;
    }

}

備註:

  • 第二 第三部分程式碼組合起來,也可以作為介面資料的統一返回格式。
  • 錯誤碼可以細分,避免各種錯誤狀態糾纏不清,難以維護
  • 此段程式碼可以直接複製到Springboot中使用,但是僅限於@RestController標註的介面,對於@Controller標註的類,未做實驗,不清楚。 而如果返回ModelAndView,請另行編寫異常處理程式碼。