[Java] Filter stack traces

things to do

Even if you create ʻExceptionby yourself with a framework such asSpringBoot` and throw an error as a known behavior, the stack trace will be displayed in the log as it is. In other words, it's clear that the cause of the error is within the application, but it's simply displaying useless information.

If the stack trace is long, it will interfere with reading comprehension, and the log capacity will increase too much, which may cause problems, so it is better not to have extra information.

Therefore, filter the stack trace.

manner

You can do this by preparing a filtering function as shown below and setStackTrace in the constructor. The package name is a string like com.wrongwrong.example, which specifies the root package.

public class MyException extends RuntimeException {
    static StackTraceElement[] filteringStackTrace(StackTraceElement[] elements) {
        return Arrays.stream(elements)
                .filter(it -> it.getClassName().startsWith("${package name}"))
                .toArray(StackTraceElement[]::new);
    }

    public MyException(String msg) {
        super(msg);
        setStackTrace(filteringStackTrace(getStackTrace()));
    }
}

Recommended Posts

[Java] Filter stack traces
[Java] Servlet filter
[Java] Create a filter
[Java] Stack area and static area
Log Java NullPointerException stack trace
[Java] Stream (filter, map, forEach, reduce)
[Java] Collection-List / Set / Map / Stack / Queue
Java reference mechanism (stack and heap)
Java
Java
How to implement Kalman filter in Java
Get caller information from stack trace (java)
Sobel filter using OpenCV on Android (Java)
Implement something like a stack in Java