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发生异常

 SpringBoot项目中,异常拦截

 

SpringBoot项目中,异常拦截

 3.2处理异常

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

但是这里就会有一个问题,不报错了,返回状态码为200,即正确

 SpringBoot项目中,异常拦截

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

SpringBoot项目中,异常拦截

 

相关文章:

  • 2021-08-03
  • 2019-09-30
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-15
猜你喜欢
  • 2018-12-07
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案