如何恢复 Spring Boot 1.5 中的默认异常映射?
How to bring back default exception mapping that was in Spring Boot 1.5?
我有一个 spring boot Jersey 应用程序,我已经将它从 Spring Boot 1.5.4
(平台:Brussels-SR3)升级到 Boot 2.0.1
(平台: Cairo-RELEASE),将 Jersey 版本从 2.25.1
提升到 2.26
。
升级之前,当应用程序抛出未处理的错误时,应用程序会返回如下响应:
{
"timestamp": 1524060527236, "status": 500, "error": "Internal Server Error",
"exception": "java.lang.IllegalStateException", "message": "<example message>",
"path": "/ws/api/example/endpoint"
}
升级后同样执行returns:
{
"timestamp": "2018-04-24T17:00:06.151+0000", "status": 500, "error": "Internal Server Error",
"message": "<example message>", "path": "/ws/api/example/endpoint"
}
我可以处理不同的时间戳格式,但丢失异常 class 是个问题。
我试过调试jersey的异常映射,但我对代码库不熟悉而且看起来很复杂。我找不到映射发生在哪里。我也找不到有关更改异常映射的文档或发行说明中的任何提及。
根据以上和下面的评论,我认为更改是在 Spring 方面。
那么,发生了什么变化以及我如何恢复旧行为?
此错误响应并非来自 Jersey。它实际上是在您将 spring-boot-starter-web
模块包含到您的项目中时生成的。基于 Andy Wilkinson's comment, we can easily override the JSON attributes by creating an ErrorAttributes
bean. To add the exception, we can just return a DefaultErrorAttributes
, creating it using the constructor flag 以包含异常。
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes(true);
}
我已经对此进行了测试,它包含了预期的异常。
我有一个 spring boot Jersey 应用程序,我已经将它从 Spring Boot 1.5.4
(平台:Brussels-SR3)升级到 Boot 2.0.1
(平台: Cairo-RELEASE),将 Jersey 版本从 2.25.1
提升到 2.26
。
升级之前,当应用程序抛出未处理的错误时,应用程序会返回如下响应:
{
"timestamp": 1524060527236, "status": 500, "error": "Internal Server Error",
"exception": "java.lang.IllegalStateException", "message": "<example message>",
"path": "/ws/api/example/endpoint"
}
升级后同样执行returns:
{
"timestamp": "2018-04-24T17:00:06.151+0000", "status": 500, "error": "Internal Server Error",
"message": "<example message>", "path": "/ws/api/example/endpoint"
}
我可以处理不同的时间戳格式,但丢失异常 class 是个问题。
我试过调试jersey的异常映射,但我对代码库不熟悉而且看起来很复杂。我找不到映射发生在哪里。我也找不到有关更改异常映射的文档或发行说明中的任何提及。
根据以上和下面的评论,我认为更改是在 Spring 方面。
那么,发生了什么变化以及我如何恢复旧行为?
此错误响应并非来自 Jersey。它实际上是在您将 spring-boot-starter-web
模块包含到您的项目中时生成的。基于 Andy Wilkinson's comment, we can easily override the JSON attributes by creating an ErrorAttributes
bean. To add the exception, we can just return a DefaultErrorAttributes
, creating it using the constructor flag 以包含异常。
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes(true);
}
我已经对此进行了测试,它包含了预期的异常。