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)
            return (error response)


$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?

图片转代码服务由CSDN问答提供 功能建议

我有一个简单的函数向我的RESTful API发出cURL请求,它返回的数据应该是 成功的要求。 我的问题是,当用户可能提供API错误数据或API无法执行请求时,我不知道如何返回错误响应(例如404s,500s)。 < p>我将如何做到这一点?

目前,我有以下内容。 在我的API客户端

 类Awesome_Api {
静态函数请求($ url,$ data,$ method)
 // cURL stuffs here ... \  n 

  $ response = Awesome_Api :: request($ url,$ data,$ method); 

现在如何从API返回错误响应代码,并在客户端处理它?<​​/ p>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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');


    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题