Java exception custom print content

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.
This link: https://blog.csdn.net/LitongZero/article/details/102767740

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

Here Insert Picture Description

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 fillInStackTracemethod, however, most of the anomalies are not doing the processing method. The basic is to call superthe method.

Here Insert Picture Description

You can see, the parent class implementation of this method is in the Throwableclass. But this method added a synchronizedlock to view the information stack. It will definitely affect performance.

The underlying implementation is nativethe 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 fillInStackTraceMethod

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;
    }

③. Print

It can be seen clearly print fewer

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/LitongZero/article/details/102767740