duanping1920 2013-01-24 03:47
浏览 73
已采纳

RESTful API错误处理

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?

  • 写回答

1条回答 默认 最新

  • doula4096 2013-01-24 03:55
    关注

    Use the header function to return error codes, like this:

    header('HTTP/1.1 500 Internal Server Error');
    

    or

    header('HTTP/1.1 404 Not found');
    

    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() and curl_errno() functions to retrieve information about the error number and message returned from the server.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?