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
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.
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+
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.
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