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