之前在日志中只打印出了异常的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(); } }