zoukankan      html  css  js  c++  java
  • 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());
        }

  • 相关阅读:
    java 之 对象与垃圾回收
    Java 之 内部类
    java 接口(interface)
    抽象类
    Java之fianl修饰符
    类的继承
    上传图片
    一般处理程序 给图片添加文字水印
    socket
    初识linq,lambda表达式
  • 原文地址:https://www.cnblogs.com/xzmxddx/p/10330845.html
Copyright © 2011-2022 走看看