How to access response body for 400 status POST request

Joseph Gabriel
Tera Contributor

I have a scenario using the RESTMessageV2 object to execute outbound REST API requests.   Depending on the data included in the request, it may fail with 400 error code, and the body of the response contains the actual information explaining why the request failed.

I need to read the body for a failed POST request so that I can create a helpful error log.   Currently, I cannot see any way to access the actual response body for 400 level responses.

Please advise.

9 REPLIES 9

Sashi K1
Kilo Guru

Try below code



var responseheaders =response.getHeaders();

  for(var err in headers) {


            gs.log(err+' Response Header '+ responseheaders[err] );


}



there is an Error in the header, see if that gets what you want!


No, this won't work, because the service I am calling returns the error information in the body — not in the headers.



See the example response below:



Status:


400 Bad Request



Response Headers:


Cache-Control →no-cache


Content-Length →263


Content-Type →application/json; charset=utf-8


Date →Mon, 06 Nov 2017 21:27:20 GMT


Expires →-1


Pragma →no-cache


Server →Microsoft-IIS/8.5


X-AspNet-Version →4.0.30319


X-Powered-By →ASP.NET


x-cw-request-id →0000000-9778-4a2f-b805-17fb3f569a7b


x-server-name →XYZ1



Response Body:


{


"code": "InvalidObject",


"message": "ticket object is invalid",


"errors": [


{


"code": "NotFound",


"message": "Service Status xxx not found for Service Board xxx",


"resource": "ticket",


"field": "status/id"


}


]


}


If they are sending JSON response, prase it



var responseBody = response.getBody();


var parser = new JSONParser();


var parsedData = parser.parse(responseBody);



gs.log(parsedData.result[0].errors);


gs.log(parsedData.result[0].errors.code);



That is what I would expect. However, response.getBody() returns null, even though there clearly is a body present.