FrankelStein
FrankelStein

Reputation: 990

Why is the stackTrace not printed when extending the ResponseEntityExceptionHandler in Spring?

I'm building a spring boot application. I'm trying to use a decent way of handling rest responses when an exceptions is raised. So I extended the ResponseEntityExceptionHandler into a class named RestResponseEntityExceptionHandler. The problem is that when an exception is thrown, the stackTrace is not printed in the console. when I delete this RestResponseEntityExceptionHandler class, the stacktrace is printed again in the console !

Here is what the RestResponseEntityExceptionHandler class looks like :

@RestControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { IllegalArgumentException.class, TechnicalException.class})
    protected void handleBadRequest(RuntimeException e, HttpServletResponse response) throws IOException 
    {
        response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }
}

I am using logback for logging.

I found some tricks to deal with that, like adding a logger.error("Details : ", exception); which works fine and prints the stackTrace but I prefer not to use a solution like that since it works only for the exceptions handeled by that class... the other exceptions wont print the stackTrace.

Any explanations why the stackTrace is not printed ? Thanx in advance.

Upvotes: 0

Views: 2221

Answers (3)

Ankush Sharma
Ankush Sharma

Reputation: 140

Staketrace is not getting printed because you are handling the ResponseEntityExceptionHandler in the RestResponseEntityExceptionHandler by RestControllerAdvice and passing only the error message in response. It you want to print it specially then add a logger in your handleBadRequest method for the error i.e. e in your case.

Upvotes: 0

Mahesh Bhuva
Mahesh Bhuva

Reputation: 764

Because You are handling Exception. If you want to print along with the handling, put logger inside ExceptionHandler methods.

Upvotes: 1

Jorge F. Sanchez
Jorge F. Sanchez

Reputation: 341

It is not "printed" because you are already handling the exception in RestResponseEntityExceptionHandler.

Upvotes: 0

Related Questions