【问题标题】:How to change ErrorAttributes of ResponseStatusException?如何更改 ResponseStatusException 的 ErrorAttributes?
【发布时间】:2018-11-06 12:22:35
【问题描述】:

如何更改在抛出 ResponseStatusException 时暴露的错误属性?

特别是我想隐藏 json 中的 exceptionerrorstatus 类型,但仅限于生产期间。

    @RestController
    public class MyController {
       @GetMapping("/test")
       public Object get() {
          throw new org.springframework.web.server.ResponseStatusException(
                 HttpStatus.Forbidden, "some message");
       }
    }

结果:

{
    "timestamp": "2018-11-06T12:16:50.111+0000",
    "status": 403,
    "error": "Forbidden",
    "exception": "org.springframework.web.server.ResponseStatusException",
    "message": "some message",
    "path": "/test"
}

【问题讨论】:

  • 我想您确实有多个配置文件,例如:dev、prod ...另外,您不使用 Spring Boot。
  • 是的,我有多个个人资料。
  • 我可以再问你一次:不要使用Spring Boot吗?
  • 对不起,是的,我也在使用 spring-boot。添加了标签。

标签: java spring spring-mvc spring-boot spring-web


【解决方案1】:

使用DefaultErrorAttributes配置

public DefaultErrorAttributes(boolean includeException)

创建一个新的DefaultErrorAttributes 实例。

参数:

includeException - 是否包含“异常”属性

注意默认没有

public DefaultErrorAttributes()

创建一个不包含“异常”属性的新 DefaultErrorAttributes 实例。

example of customizing error

【讨论】:

  • 所以我会覆盖DefaultErrorAttributeserrorAttributes.remove("path") 等?
  • @membersound 或致电Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, false);
  • @membersound IMO 这个答案清楚地解决了问题:为每个配置文件实现 DefaultErrorAttributes。
猜你喜欢
  • 2022-11-04
  • 2021-07-20
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 2015-05-21
相关资源
最近更新 更多