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