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

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?

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

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

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

 类Awesome_Api {
静态函数请求($ url,$ data,$ method)
 {
 // cURL stuffs here ... \  n 
 if(成功)
 {
返回(成功响应)
} 
其他
 {
返回(错误响应)
} 
} 
} 
   
 
 

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

    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.

    打赏 评论

相关推荐 更多相似问题