2017-08-27 18 views
0

我在回傳和處理應用程序中的錯誤時遇到了困難。該應用程序基於PHP(版本5.3.29)。PHP:通過HTTP POST返回錯誤並在CURL中引用他們

我有一個頁面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狀態碼並輸出

預約已被取消

我在這裏做錯了什麼,無論是在返回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(); 

    } 
}); 

在此先感謝。

回答

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 
} 
+0

謝謝布萊恩,這個伎倆。 –