As a Javaer, you know that spring-related projects mostly catch exceptions globally and wrap them up as a more human reminder to the front end. And after the exception is captured, it is generally recorded in the log (call stack information of the exception), which is convenient for development and troubleshooting.

There is an obvious problem, the system usually will have more business exceptions, namely if the user does not exist, right state and so on business exceptions, if also records all exception stack information, then people will feel a little waste of disk space, and the underlying framework of stack information has little guidance significance to troubleshoot problems. Here’s a picture (limited in scope, with a lot of stack information underneath) :

The optimized Spring global exception handler handles business exceptions

@ExceptionHandler(BizRuntimeException.class) public Result<? > handleBusinessRuntimeException (BizRuntimeException e) {/ / only record the class associated with the system call stack information, or mayfly only. At the beginning of the class package name will be logged in the LOG. The error (" business exceptions: {} ", ThrowableUtils getStackTraceByPn (e, "mayfly.")); return Result.error(e.getErrorCode(), e.getMessage()); }Copy the code

The ThrowableUtils class, refer to the Throwable#printStackTrace method

@param e exception @param packagePrefix packagePrefix @return stack information */ public static String getStackTraceByPn(Throwable e, String packagePrefix) { StringBuilder s = new StringBuilder("\n").append(e); for (StackTraceElement traceElement : e.getStackTrace()) { if (! traceElement.getClassName().startsWith(packagePrefix)) { break; } s.append("\n\tat ").append(traceElement); } return s.toString(); }Copy the code

Log information after adjustment

After adjustment and optimization, only the class call stack information related to the system package is recorded when service exceptions are recorded. Remove the call stack of the underlying framework such as Spring, reduce the log disk space, and simplify the troubleshooting of service exceptions. More details can be found at gitee.com/objs/mayfly