Prevent stack trace logging for custom exception in Spring Boot application
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+
Call overloaded super constructor to avoid showing the stacktrace in response.
public class ProductCustomException extends Exception{
private static final long serialVersionUID = -291211739734090347L;
public ProductCustomException(String message) {
super(message,null,false,false);
}
}
Super loaded Constructor from Exception Class
protected Exception(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
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.
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