简体   繁体   中英

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.

它不是“打印”的,因为您已经在 RestResponseEntityExceptionHandler 中处理异常。

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

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 ie e in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM