Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Java exception custom print content
Background: In development, we may use the custom exception, however, the custom exception when the print log, print content more often.
1. print custom exception
You can see that although we are using a custom exception, but when thrown, or will print out all the information stack.
2. View source
By looking at the source code, we can see that, when an exception is thrown, the program will invoke this exception fillInStackTrace
method, however, most of the anomalies are not doing the processing method. The basic is to call super
the method.
You can see, the parent class implementation of this method is in the Throwable
class. But this method added a synchronized
lock to view the information stack. It will definitely affect performance.
The underlying implementation is native
the method to call the C language.
3. Solution
①. Writing custom exception
// 此处为lombok注解
@Getter
@AllArgsConstructor
public enum ExceptionEnum {
AUTH(1, "认证异常")
;
private Integer code;
private String msg;
}
public class AppException extends RuntimeException {
public AppException(ExceptionEnum exceptionEnum) {
super(exceptionEnum.getMsg());
}
// 关键
@Override
public Throwable fillInStackTrace() {
return this;
}
public static void main(String[] args) {
throw new AppException(ExceptionEnum.AUTH);
}
}
②. Rewrite fillInStackTrace
Method
After override this method, it will only print the first message, so not only can save log space for easy viewing, but also can improve part performance.
@Override
public Throwable fillInStackTrace() {
return this;
}