Prevent stack trace logging for custom exception in Spring Boot application

前端 未结 4 1073
走了就别回头了
走了就别回头了 2021-02-01 17:06

Is there a way in Spring Boot (mvc) to log a custom exception and throw it without its stack trace being visible in the log file? But for any other exception st

相关标签:
4条回答
  • 2021-02-01 17:17

    If you don't need the stack trace you can suppress the stack trace by overriding fillInStackTrace in your exception class.

    public class DuplicateFoundException extends RuntimeException {
        @Override
        public synchronized Throwable fillInStackTrace() {
            return this;
        }
    }
    

    When you invoke e.printStackTrace() then no stack trace will be printed.

    See also this blog post.

    0 讨论(0)
  • 2021-02-01 17:26

    Be wary of Spring Boot DevTools.

    Despite NEVER being the default for server.error.include-stacktrace, if you include Spring Boot DevTools it overides to ALWAYS.

    If you're interested in more detail, see this commit, which became part of Spring Boot 2.1.0+

    0 讨论(0)
  • 2021-02-01 17:41

    Solution was to leave the exception handling to spring boot, so that custom exception is not logged and any other is logged by default. I removed the @ControllerAdvice and also the logging statements from the rest controller and added logging statement to custom exception constructor.

    public DuplicateFoundException(String message) {
        super(message);
        LOGGER.warn(message);
    }
    

    I am not sure if this is the best approach, but now I have custom exception logging only at one place and don't have to repeat the log statement for every exception or see its stack trace or any other error message in the logs.

    0 讨论(0)
  • 2021-02-01 17:42

    I'm using Spring Boot 2+ just add this line to your application.properties:

    server.error.include-stacktrace=never

    https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/web/ErrorProperties.IncludeStacktrace.html

    0 讨论(0)
提交回复
热议问题