Java自定義異常類以及異常攔截器


  自定義異常類不難,但下面這個方法,它的核心是異常攔截器類。
  就算是在分布式系統間進行傳遞也可以,只要最頂層的服務有這個異常攔截器類(下例是在 springboot 項目中)

1、自定義異常類,繼承自 RuntimeException,參數只有一個異常錯誤碼

public class BingException extends RuntimeException {
    private final int code;

    public BingException(int code) {
        this.code = code;
    }

    public int getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.toString();
    }

    public String toString() {
        return "系統異常,異常編碼:" + this.code;
    }
}

 

2、異常攔截器類 

package cn.jiashubing.config;

import cn.jiashubing.common.BingException;
import cn.jiashubing.result.ResultModel;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author jiashubing
 * @since 2019/6/17
 */
@ControllerAdvice
public class BingExceptionHandler {

    //自定義異常返回對應編碼
    @ExceptionHandler(BingException.class)
    @ResponseBody
    public ResultModel handlerBingException(BingException e) {
        return new ResultModel(false, "token_outtime");
    }

    //其他異常報對應的信息
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultModel handlerSellException(Exception e) {
        return new ResultModel(false, "系統出錯,錯誤信息為:" + e.getMessage());
    }

}

  

也可以用下面復雜一點的辦法

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;

/**
 * @author jiashubing
 * @since 2018/10/29
 */
@ControllerAdvice
public class ExceptionHandle {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    /**
     * 異常處理
     * @param e 異常信息
     * @return 返回類是我自定義的接口返回類,參數是返回碼和返回結果,異常的返回結果為空字符串
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        //自定義異常返回對應編碼
        if (e instanceof BingException) {
            BingException ex = (BingException) e;
            return new Result<>(ex.getCode(), "");
        }
        //其他異常報對應的信息
        else {
            logger.info("[系統異常]{}", e.getMessage(), e);
            return new Result<>(-1, "");
        }

    }
}

 

PS:還可以返回不同的response 狀態,默認是200,@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 這個是返回500狀態

 

3、然后在代碼里拋異常就可以直接拋出異常了

throw new BingException(5);

 

原創文章,歡迎轉載,轉載請注明出處!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM