7

Currently, I'm getting HttpResponseException, which has only statusCode. How can I get complete body of response?

Here is code I'm using

restClient = new RESTClient("http://${Server}")
try {
    HttpResponseDecorator resp = restClient.post(path,body,requestContentType)     
        as HttpResponseDecorator
    return JSONObject.fromObject(resp.getData()).get("topKey","");
    }
catch (HttpResponseException e) {
            error(e.toString())
    }

And it only output this:

[oaf.error] groovyx.net.http.HttpResponseException: Internal Server Error
Vyacheslav
  • 73
  • 1
  • 4

2 Answers2

7

Add custom failed response handler:

        restClient = new RESTClient("http://${Server}")
        restClient.handler.failure = { resp, data ->
            resp.setData(data)
            String headers = ""
            resp.headers.each {
                headers = headers+"${it.name} : ${it.value}\n"
            }
            throw new HttpResponseException(resp.getStatus(),"HTTP call failed. Status code: ${resp.getStatus()}\n${headers}\n"+
                                            "Response: "+(resp as HttpResponseDecorator).getData())
        }
Slavik
  • 1,488
  • 1
  • 15
  • 24
  • I find it strange that `data` is not already included in `resp`, given that `resp.setData()` is a non-public method. – jaco0646 Jul 12 '19 at 18:22
0

Actually, you can extract the full response from the exception thrown. For example if your caught exception is e and response body JSON should contain a field called myCustomErrorCode, you can check its value by looking at e.response.data.myCustomErrorCode in addition to e.statusCode.

Michał Kosmulski
  • 9,855
  • 1
  • 32
  • 51