zoukankan      html  css  js  c++  java
  • Spring异常集中处理和日志集中打印

    使用@ControllerAdvice和@ExceptionHandler处理Controller层的异常:

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
        /**
         * 处理所有不可知的异常
         * @param e
         * @return
         */
        @ExceptionHandler(Exception.class)
        @ResponseBody
        AppResponse handleException(Exception e){
            // 记录日志
            LOGGER.error(e.getMessage(), e);
            // 统一返回值
            AppResponse response = new AppResponse();
            response.setFail("服务器错误");
            return response;
        }
    
        /**
         * 处理自定义异常
         * @param e
         * @return
         */
        @ExceptionHandler(CustomException.class)
        @ResponseBody
        AppResponse handleCustomException(CustomException e){
            LOGGER.error(e.getMessage(), e);
    
            AppResponse response = new AppResponse();
            response.setFail(e.getMessage());
            return response;
        }
    }
    

     对于需要给前台返回特定错误信息的异常,手动抛出CustomException,并添加错误信息,通过handleCustomException返回,其他异常信息通过handleException处理,返回服务器异常,所有异常均打印日志

  • 相关阅读:
    研究生
    linux下C++开发工具
    GCC and G++ install
    linux yum命令详解
    OpenCV:SURF算法浅析
    linux内核(kernel)版本号的意义
    常见排序算法
    bash:command not found
    C++ 面向对象(数据封装)
    HTML5 script 标签的 crossorigin 和integrity属性的作用
  • 原文地址:https://www.cnblogs.com/lishaojun/p/11074955.html
Copyright © 2011-2022 走看看