The api I'm calling returns a json object of validation errors with the HTTP code 400. I implemented the client using PHP's curl library, but on error curl_exec
returns false. How can I get the response body on error?
Note that I am setting curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Next, we've set the CURLOPT_POST option to TRUE to set the request method to HTTP POST. Further, we need to use the CURLOPT_POSTFIELDS option to set the POST data that we want to submit along with the request. Finally, we've used the curl_exec function to execute the cURL request.
Functions of cURL in PHP curl_error — It will return the string which represents the error for the particular current session.
"You can use the curl_error() function". Proceeds to use curl_errno() in the example. :) @RomanPerekhrest That is terrible advice. Not only is it debatable if a 404 is "an error", curl_exec() will also not return the body anymore if you enable CURLOPT_FAILONERROR .
You can unset CURLOPT_FAILONERROR
for once. And adding your error status code to CURLOPT_HTTP200ALIASES
as expected might also help.
curl_setopt($conn, CURLOPT_FAILONERROR, false);
curl_setopt($conn, CURLOPT_HTTP200ALIASES, (array)400);
(libcurl also has a CURLOPT_ERRORBUFFER
, but you cannot use that option from PHP.)
Btw, curl behaves correctly by not returning the response body in case of 4xx errors. Not sure if that can be overriden. So you might have to migrate to PEAR HTTP_Request2
or a similar HTTP request class where you can deviate from the standard.
I was able to get content from a 400 response by setting FAILONERROR to false, WITHOUT having to also alias 400 as a normal 200 response.
Add this:
curl_setopt($ch, CURLOPT_HTTP200ALIASES, array(400));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With