異常統一處理

一,異常統一處理java

1,自定義異常web

package com.onloon.scrm.common.exception;

import com.onloon.scrm.common.enums.ResultCodeEnum;
import lombok.Getter;

/**
 * 業務層異常*/
@Getter
public class BusinessException extends RuntimeException {

    /**
     * 錯誤編碼
     */
    private int errorCode = ResultCodeEnum.NORMAL_ERROR.getCode();

    /**
     * 錯誤數據
     */
    private Object errorData;

    /**
     * 
     */
    private static final long serialVersionUID = -8582206887663268981L;

    public BusinessException() {
        super();
    }

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

    public BusinessException(ResultCodeEnum resultCodeEnum, String message) {
        super(message);
        this.errorCode = resultCodeEnum.getCode();
    }

    public BusinessException(int errorCode, Object errorData, String message) {
        super(message);
        this.errorCode = errorCode;
        this.errorData = errorData;
    }

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

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

    protected BusinessException(String message, Throwable cause, boolean enableSuppression,
            boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

2,定義攔截器spring

package com.onloon.scrm.pc.web.controller;

import com.onloon.scrm.common.beans.Result;
import com.onloon.scrm.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

/**
 * 業務異常統一處理器*/
@ControllerAdvice
@Slf4j
public class BusinessExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public Result<String> exceptionHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        log.info("發生未捕獲異常:", e);
        if (e instanceof BusinessException) {
            return Result.failure((BusinessException) e);
        } else if (e instanceof NullPointerException || e instanceof SQLException || e instanceof IllegalStateException) {
            return Result.failure("服務器開小差了,請儘快聯繫服務人員");
        } else {
            return Result.failure("服務器開小差了,請稍後重試");
        }
    }

}
相關文章
相關標籤/搜索