Is there a way in Spring Boot (mvc) to register a custom exception and throw it if its stack trace is not visible in the log file ? But for any other exception, they still see the stack trace.
Long explanation:
I use Spring Boot to create a simple rest service. I like that for custom exceptions there is no stack trace in the logs by default , and a json response is created with basic information about the exception (status, error, message).
The problem is that it does not create a log entry at all , so I would have to do it manually:
Custom exception
@ResponseStatus(value = HttpStatus.CONFLICT) public class DuplicateFoundException extends RuntimeException { public DuplicateFoundException(String message) { super(message); } }
Throw exception in service method (in @RestController)
if (!voteDao.findByItemAndUser(item, voteDto.getUserId()).isEmpty()) { log.warn("... already voted ...");
Having more exceptions causes the log statement to be placed before each throw, which I consider to be bad. I tried removing all the log statements from the service method and created @ControlledAdvice where I would log all user exceptions and just throw them to still get good json:
@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 only the log entry, but also the stack trace for user exceptions and cannot find a way to prevent this. I think the problem is because she throws it again. A possible solution would be to create a custom class for the exception, which I will return instead, but I don't like the idea, since the marshalling exception seems to work fine.
Any clues? Thanks.
java spring spring-boot logging exception-handling
rhorvath
source share