【问题标题】:Stacktrace of custom exception is not printed in Spring Boot 2.3Spring Boot 2.3 中不打印自定义异常的 Stacktrace
【发布时间】:2020-06-19 10:12:19
【问题描述】:

对于使用@ResponseStatus 注释的自定义异常,不会在控制台中打印错误堆栈跟踪

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalErrorException extends RuntimeException {

  public InternalErrorException(String message) {
    super(message);
  }

  public InternalErrorException(String message, Throwable throwable) {
    super(message, throwable);
  }
}

抛出像throw new InternalErrorException("error", e)这样的异常,除非我删除注释@ResponseStatus,否则永远不会在控制台中打印堆栈跟踪

如何在保留注释@ResponseStatus 的同时打印它?

【问题讨论】:

  • 你有什么问题?
  • 如何打印?
  • 您在打印堆栈跟踪吗?你能分享你是你试图打印它的代码吗
  • 你读过“Exception Handling in Spring MVC”吗?
  • 当代码抛出未处理的异常时,异常会一直渗透到 Tomcat,然后将其记录下来。当异常用@ResponseStatus 注释时,Spring 拦截异常并将其转换为response.sendError(...) 调用以生成具有给定状态代码的标准HTTP 响应,因此没有异常渗透到Tomcat,因此没有日志记录完毕。 Spring 代码可以记录异常,如果您设置 warnLogCategory 属性如前面的链接所示,但不记录堆栈跟踪。

标签: java spring spring-boot logging


【解决方案1】:

Annotation Type ResponseStatus API doc

警告:在异常类上使用该注解,或设置该注解的原因属性时,将使用HttpServletResponse.sendError方法。

使用 HttpServletResponse.sendError,响应被认为是完整的,不应再写入任何内容。此外,Servlet 容器通常会编写一个 HTML 错误页面,因此会使用不适合 REST API 的原因。对于这种情况,最好使用 ResponseEntity 作为返回类型并完全避免使用@ResponseStatus。

HttpServletResponse.sendError 不会抛出您的错误,我猜它永远不会因此而被记录。

也许您想为该异常实现异常处理程序以记录它。

Related question

【讨论】:

  • 我通过其他方法了解异常处理程序。我只是想找出是否有处理这个问题的捷径。类似于server.error.include-stacktrace的东西
  • 我认为安德烈亚斯在他对您问题的评论中所说的话也很好地回答了这个问题。您无法做到这一点,答案在文档中。
猜你喜欢
  • 2019-06-03
  • 2019-12-12
  • 2021-12-13
  • 2019-12-10
  • 2014-12-16
  • 2021-07-10
  • 1970-01-01
  • 2020-05-26
  • 2023-03-04
相关资源
最近更新 更多