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

  • 相关阅读:
    bzoj4849: [Neerc2016]Mole Tunnels
    bzoj 4069~4071 APIO2015
    bzoj 4885: [Lydsy2017年5月月赛]长方体
    bzoj4891: [Tjoi2017]龙舟
    bzoj4892: [Tjoi2017]dna
    bzoj 3159: 决战
    bzoj3672: [Noi2014]购票
    bzoj4738: 汽水
    bzoj 4737: 组合数问题
    bzoj 4872: [Shoi2017]分手是祝愿
  • 原文地址:https://www.cnblogs.com/lishaojun/p/11074955.html
Copyright © 2011-2022 走看看