Spring boot edit json exception with data from ser

2019-07-30 13:39发布

My spring boot application works like a middleman. It waits for a request, then formats this request and sends to the server and returns server response to request sender. However when I get response error response from server (For example with status code 400 Bad Request) I want to modify default spring boot JSON exception body by adding error cause which was returned from server in JSON format.

Response from server:

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 returns exception:

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

I want to edit spring's exception field "message" with server's returned "error_message" value. But it seems that I can't even get Response body because spring boot automatically throws default exception.

1条回答
叛逆
2楼-- · 2019-07-30 14:02

My understanding is that you need to provide your own exception mapper. The one used now is the default ErrorController added by autoconfiguration.

The correct way is to define your own ResponseEntityExceptionHandler

you can read about custom Exceptionmappers here

查看更多
登录 后发表回答