SpringBoot項目中,異常攔截


SpringBoot自帶異常攔截@ControllerAdvice

1.創建一個SellerExceptionHandler類打上@ControllerAdvice標簽

@ControllerAdvice
public class SellExceptionHandler {
}

2.創建異常處理程序@ExceptionHandler(value = SellerAuthorizeException.class)表示攔截的異常為SellerAuthorizeException異常

    /**
     * 攔截登錄異常
     * @return
     */
    @ExceptionHandler(value = SellerAuthorizeException.class)
    public ModelAndView handlerAuthorizeException(){
        return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/toLogin");
    }

3.處理異常,返回json格式內容,並且改變錯誤狀態碼

3.1發生異常

 

 

 3.2處理異常

    @ExceptionHandler(value = SellException.class)
    @ResponseBody
    public ResultVO handlerSellException(SellException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }

但是這里就會有一個問題,不報錯了,返回狀態碼為200,即正確

 

3.3@ResponseStatus(HttpStatus.FORBIDDEN),設定返回狀態碼

    @ExceptionHandler(value = SellException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResultVO handlerSellException(SellException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }

 


免責聲明!

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



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