I have a simple function that makes a cURL request to my RESTful API, and it returns data as it should when a successful request is made. My problem is, when a user perhaps gives the API wrong data or the API can’t do what is requested, I don’t know how to return error responses (e.g. 404s, 500s).
How would I go about doing this?
At the moment I have the following. In my API client
class Awesome_Api {
static function request($url, $data, $method)
{
// cURL stuffs here...
if (successful)
{
return (success response)
}
else
{
return (error response)
}
}
}
and
$response = Awesome_Api::request($url, $data, $method);
Now how do I return an error response code from the API, and handle it in the client end?
Use the
headerfunction to return error codes, like this:or
It is very important that you make sure nothing has been written to the output before calling this function, otherwise it will not work as you expect.
In your client API, you can use the
curl_error()andcurl_errno()functions to retrieve information about the error number and message returned from the server.