How to get complete response for Groovy RestClient failed response
Asked Answered
R

2

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
Rebec answered 3/3, 2015 at 23:20 Comment(0)
B
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())
        }
Brigidbrigida answered 3/3, 2015 at 23:24 Comment(1)
I find it strange that data is not already included in resp, given that resp.setData() is a non-public method.Hadden
A
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.

Argyrol answered 10/12, 2015 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.