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 still see the stack trace.
Long explanation:
I am using spring boot to create a simple rest service. I like that for a custom exceptions there is no stack trace in the logs by default and JSON response is created with the basic exception details (status, error, message).
The problem is that it also creates no log entry at all, therefore I would have to do this manually:
Custom Exception
@ResponseStatus(value = HttpStatus.CONFLICT)
public class DuplicateFoundException extends RuntimeException {
public DuplicateFoundException(String message) {
super(message);
}
}
Exception throwing in service method (in @RestController)
if (!voteDao.findByItemAndUser(item, voteDto.getUserId()).isEmpty()) {
log.warn("... already voted ..."); //TODO: don't do this for every throw
throw new DuplicateFoundException("... already voted ...");
}
Having more exceptions leads to placing log statement before each throw, which is a bad approach I think. I've tried removing all the log statements from the service method and created @ControllerAdvice
where I would log all the custom exceptions and just re-throw them so I still get the nice JSON as before:
@ControllerAdvice
public class RestExceptionHandler {
private static final Logger log = Logger.getLogger(RestExceptionHandler.class);
@ExceptionHandler
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
log.warn(e.getMessage());
} else {
log.error("...");
}
throw e;
}
}
Now the problem is that I see not just the log entry, but also the stack trace for custom exceptions and can't find a way how to prevent this. I think the problem is caused by throwing it again. A possible solution could be to create a custom class for exception which I will return instead, but I dislike the idea since exception marshalling seems to work fine.
Any hints?