Spring web 異常統(tǒng)一處理

異常類(lèi)型

  • 檢查異常

檢查異常需要捕獲或者在函數(shù)簽名中拋出異常,一般是IO異常,通常處理方式是,如果需要重試則try cach再試,如果不需要處理,則轉(zhuǎn)為非檢查異常,或者是在追加到函數(shù)簽名中。

  • 非檢查異常

不需要額外處理

使用@RestControllerAdvice統(tǒng)一處理異常

@RestControllerAdvice
public class ExceptionHandlerConfiguration {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(ExceptionHandlerConfiguration.class);

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResultBody> handler(Exception e) {
        if (e instanceof AbstractException) {
            AbstractException exception = (AbstractException) e;
            if (exception instanceof SystemException) {
                LOGGER.error("開(kāi)發(fā)異常", e);
            } else {
                LOGGER.debug("異常", e);
            }
            return new ResponseEntity<ResultBody>(
                    ResultBody.failed().code(exception.getCode())
                            .msg(e.getMessage()),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
        LOGGER.error("系統(tǒng)錯(cuò)誤", e);
        return new ResponseEntity<ResultBody>(
                ResultBody.failed().code(ErrorCode.ERROR.getCode())
                        .msg(e.getMessage() + Arrays
                                .toString(e.getStackTrace())),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

抽象異常

public abstract class AbstractException extends RuntimeException {
    private Integer code;

    public AbstractException(Integer code, String message, Object... params) {
        super(MessageFormat.format(message, params));
        this.code = code;
    }

    public AbstractException(ErrorCode code, String message, Object... params) {
        super(MessageFormat.format(message, params));
        this.code = code.getCode();
    }

    public Integer getCode() {
        return code;
    }
}

業(yè)務(wù)異常


image.png

例如

public class RequestBodyBadException extends AbstractException {
    public RequestBodyBadException(String message, Object... params) {
        super(ErrorCode.BAD_REQUEST, message, params);
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容