我在回复和处理应用程序中的错误方面遇到了困难。该应用程序基于PHP(版本5.3.29)。
我有一页 TakePayment.php ,其结构如下:
try
{
if( <<some condition>> )
{
<<log error>>
header("HTTP/1.1 500 Internal Server Error");
exit;
}
<<take payment>>
//if payment was ok, emit and empty json string
Header('Content-Type: application/json');
echo "{}";
}
catch( Exception $e )
{
<<log error>>
header("HTTP/1.1 500 Internal Server Error");
exit;
}
我有另一页 CancelAppointment.php ,其中包含以下代码:
$ch = curl_init();
$timeout = 5;
$url = 'https://############/TakePayment.php';
$formData = array('isCancellationPayment' => '1', 'booking_id' => $bookingId);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($formData));
$data = curl_exec($ch);
if(!curl_errno($ch))
{
?>
<p>Appointment has been cancelled </p>
<?
}
else
{
echo 'Fatal error taking payment, please contact PsychFinder support with the following information: ' . curl_error($ch);
exit;
}
curl_close($ch);
我遇到的问题是if(!curl_errno($ ch))块没有发现TakePayment.php页面返回500状态代码并输出
< p>约会已被取消
我在这里做错了,无论是返回500错误还是用CURL捕获它。
当我使用客户端Ajax(在应用程序的另一部分)调用同一页面时,它按预期工作并且如果存在付款问题则显示错误,因此它让我认为我的CURL使用是错的?
$.ajax({
url: "/TakePayment.php",
method: 'POST',
data: {'booking_id': jsonData["bookingid"]},
dataType: 'html',
cache: false,
success: function(data)
{
},
error: function( jqXHR, textStatus, errorThrown)
{
document.write("Error taking payment for session. Please contact Support: " + errorThrown);
throw new Error();
}
});
提前致谢。
答案 0 :(得分:1)
由于您遇到的问题是TakePayment.php页面返回了500状态代码,因此在执行cURL请求时只需要更多错误检查。从技术上讲,curl_errno用于cURL错误,而不是在另一端发生的错误。下面的代码片段是我在脚本中使用的,每天执行许多请求。请注意,即使在我收到响应后,我仍然需要检查HTTP状态代码,如果有cURL错误则无关。
// If there was a connection w/ response
if( $response = curl_exec( $ch ) )
{
// Make sure the response indicates a success HTTP status code
if( curl_getinfo( $ch, CURLINFO_HTTP_CODE ) != '200' )
{
// ... error at server ...
}
// The request was good
else
{
// ... do something ...
}
}
// If there was no successful connection or response
else
{
$curl_info = curl_getinfo( $ch );
// $curl_info may be useful in debugging
}