【问题标题】:Spring boot edit json exception with data from server responseSpring Boot 使用来自服务器响应的数据编辑 json 异常
【发布时间】:2017-09-23 21:53:27
【问题描述】:

我的 Spring Boot 应用程序像中间人一样工作。它等待一个请求,然后格式化这个请求并发送到服务器并将服务器响应返回给请求发送者。但是,当我从服务器获得响应错误响应时(例如状态代码为 400 Bad Request),我想通过添加从服务器以 JSON 格式返回的错误原因来修改默认的 Spring Boot JSON 异常主体。

来自服务器的响应:

Http status: 400
{
    "type": "InvoiceDto",
    "currency": "EUR",
    "error_code": "NO_AMOUNT"
    "error_message": "amount is not set"
    "invoice_status": "FAILED",
    "payment_id": "20516324",
    "order_id": 1209,
  }

Spring boot 返回异常:

{
  "timestamp": 1493211638359,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.web.client.HttpClientErrorException",
  "message": "400 Bad Request",
  "path": "/sms"
}

我想用服务器返回的“error_message”值来编辑spring的异常字段“message”。但似乎我什至无法获得响应正文,因为spring boot会自动抛出默认异常。

【问题讨论】:

    标签: java spring-mvc spring-boot error-handling


    【解决方案1】:

    我的理解是你需要提供自己的异常映射器。现在使用的是自动配置添加的默认ErrorController

    正确的方法是定义自己的ResponseEntityExceptionHandler

    您可以阅读自定义 Exceptionmappers here

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      相关资源
      最近更新 更多