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()); }