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

  • 相关阅读:
    vue 基础 模板
    常见的JS语言错误总汇
    面向对象两大编程思想
    15条你可能不知道的JS高效技巧
    django简介
    ping连通性
    IP地址解释
    web网页请求以及网络联网的一些过程
    HTTP和HTTPS协议
    TCP和UDP
  • 原文地址:https://www.cnblogs.com/xzmxddx/p/10330845.html
Copyright © 2011-2022 走看看