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处理,返回服务器异常,所有异常均打印日志

  • 相关阅读:
    POJ测试数据合集
    POJ1724ROADS
    关闭进程的数据库
    config上传设置
    tfs 撤销挂起的更改
    cn_visual_studio_team_foundation_server_2010_x86_x64_dvd_531909
    js 中文转义
    文件下载乱码
    杀死数据库进程
    Python基础综合练习
  • 原文地址:https://www.cnblogs.com/lishaojun/p/11074955.html
Copyright © 2011-2022 走看看