PHP - REST API - http 标头 - 错误处理 [英] PHP - REST API - http headers - error handling
问题描述
我试图将 HTTP 标头与 XML 一起返回,说明进程是否成功.
I am trying to return a HTTP header together with XML stating whether a process has been successful or not.
在开发我的 API 时,这一切似乎都运行良好,我正在从同一服务器对 API 进行测试调用,并将相关的标头状态代码与 XML 一起获取.但是,当我再次测试但从其他服务器调用 API 时遇到了问题.
This all appeared to be working fine whilst developing my API, I was making test calls to the API from the same server and getting the relevant header status code together with the XML. However, when I test this again but calling the API from other server and am encountering a problem.
如果响应是 200,那么我得到响应 XML.如果有错误,我会收到标头状态代码 OK 但没有收到错误 XML.我玩弄了错误消息传递函数,并注意到如果我注释掉 header($status_header);
会发送错误 XML.谁能解释一下为什么会发生这种情况?
If the response is 200 then I get the response XML. If there is an error, I receive the header status code OK but get no error XML. I have played around wit the the error messaging function and noticed that if I comment out header($status_header);
the error XML is sent. Can anyone shed some light as to why this might be happening?
static function errorResponse($status = 400, $body = '') {
$status_message = APIResponse::getStatusCodeMessage($status);
$status_header = 'HTTP/1.1 ' . $status . ' ' . $status_message;
// set the HTTP status
header($status_header);
if($body == '') {
// create the message if none is passed
$body = '';
switch($status)
{
case 401:
$body = 'You must be authorized to view this page.';
break;
case 404:
$body = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
break;
case 500:
$body = 'The server encountered an error processing your request.';
break;
case 501:
$body = 'The requested method is not implemented.';
break;
}
}
$response_xml = '<?xml version="1.0" encoding="utf-8"?>
<error>
<date>' . date("D, d M Y H:i:s", time()) . '</date>
<status>' . $status . ' - ' . $status_message . '</status>
<message><![CDATA[' . $body . ']]></message>
</error>';
return $response_xml;
exit;
}
推荐答案
我现在已经对此进行了排序,这是我的包含 CURL 函数的类的错误,与此类无关.
I've now sorted this, it was an error with my class containing CURL functions, nothing to do with this class.
这篇关于PHP - REST API - http 标头 - 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!