zoukankan      html  css  js  c++  java
  • 统一全局异常处理将出错的栈信息打印到日志中

    之前在日志中只打印出了异常的getmessage(),查看日志排查错误时特别麻烦,很难快速定位到出错的方法,然后我就想如果能将异常的栈信息直接打印到日志中该多好,但是,直接通过exception自身的的方法无法得到栈信息,百度了一下,发现需要先将异常的栈信息读入到字符流中,然后将字符流tostring()转换成字符串就行了,代码如下:

    /**
     * 全局统一异常处理
     * @author Holley
     * @create 2018-05-24 14:59
     **/
    @RestControllerAdvice
    public class GlobalExceptionHandler {
        private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
        @ExceptionHandler(value = Exception.class)
        public Response handler(Exception e){
            Response r = new Response();
            if (e instanceof SelectNoFindException){
                SelectNoFindException selectNoFindException = (SelectNoFindException) e;
                r.setMessage(selectNoFindException.getErromessage());
                r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
                log.error(selectNoFindException.getMessage());
                return r;
            } else {
                r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
                r.setMessage("系统错误");
                log.error(errInfo(e));
                return r;
            }
        }
        public static String errInfo(Exception e) {
            StringWriter sw = null;
            PrintWriter pw = null;
            try {
                sw = new StringWriter();
                pw = new PrintWriter(sw);
                // 将出错的栈信息输出到printWriter中
                e.printStackTrace(pw);
                pw.flush();
                sw.flush();
            } finally {
                if (sw != null) {
                    try {
                        sw.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                if (pw != null) {
                    pw.close();
                }
            }
            return sw.toString();
        }
    }
  • 相关阅读:
    Go--指针
    Go--struct
    Go--函数
    Go基础
    流程控制
    Go前言
    变量与常量
    Django(三):HttpRequest和HttpResponse
    Django(二):url和views
    tensorflow(一):图片处理
  • 原文地址:https://www.cnblogs.com/zhlblogs/p/9549943.html
Copyright © 2011-2022 走看看