2013-03-31 109 views
2

我在PHP中使用GoCardless's API版本來處理我網站上的付款。但是,當他們的API返回錯誤時,我想向用戶顯示更有效的錯誤。檢索數組中的錯誤消息

我有一半的方式有,但我不知道是否有無論如何,我可以做到以下幾點:

如果我有以下錯誤:

Array ([error] => Array ([0] => The resource has already been confirmed))

反正是有隻提取部分與PHP?

我的代碼:

try{ 
     $confirmed_resource = GoCardless::confirm_resource($confirm_params); 
    }catch(GoCardless_ApiException $e){ 
     $err = 1; 
     print '<h2>Payment Error</h2> 
     <p>Server Returned : <code>' . $e->getMessage() . '</code></p>'; 
    } 

感謝。

UPDATE 1:觸發異常

代碼:

$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
if ($http_response_code < 200 || $http_response_code > 300) { 

    // Create a string 
    $message = print_r(json_decode($result, true), true); 

    // Throw an exception with the error message 
    throw new GoCardless_ApiException($message, $http_response_code); 

} 

更新2: - >print_r($e->getMessage())輸出:

Array ([error] => Array ([0] => The resource has already been confirmed))

+0

'$ errorArray ['error'] [0]' – prodigitalson

回答

0

我發現了這個問題,從$e->getMessage()輸出是一個簡單的字符串,而不是一個數組。

所以我編輯了Re​​quest.php文件到以下幾點:

$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
if ($http_response_code < 200 || $http_response_code > 300) { 

    // Create a string <<-- THE PROBLEM -->> 
    // $message = print_r(json_decode($result, true), true); 

    $message_test = json_decode($result, true); 

    // Throw an exception with the error message 
    // OLD - throw new GoCardless_ApiException($message, $http_response_code); 
    throw new GoCardless_ApiException($message_test[error][0], $http_response_code); 

} 

,然後我的PHP文件:

try{ 
    $confirmed_resource = GoCardless::confirm_resource($confirm_params); 
}catch(GoCardless_ApiException $e){ 
    $err = 1; 
    $message = $e->getMessage(); 

    print '<h2>Payment Error</h2> 
    <p>Server Returned : <code>' . $message . "</code></p>"; 
} 

和頁面輸出:

Payment Error

Server Returned : The resource has already been confirmed

1

$e->getMessage()似乎返回一個所述的方法有索引'錯誤'的數組至少是一個數組包含消息文本。如果你問我這是糟糕的API設計

但是您可以訪問郵件正文是這樣的:

try{ 
    $confirmed_resource = GoCardless::confirm_resource($confirm_params); 
}catch(GoCardless_ApiException $e){ 
    $err = 1; 
    $message = $e->getMessage(); 
    $error = $message['error']; 
    print '<h2>Payment Error</h2> 
    <p>Server Returned : <code><' . $error[0] . "</code></p>"; 
} 
+3

+1爲正確的答案。但是,在api開發人員返回一個數組來代替應該是一個字符串的地方是糟糕的。 – prodigitalson

+2

是啊!我目前正在搜索文檔。也許我會找到這個解釋 – hek2mgl

+0

即使你找到一個解釋它不相關的國際海事組織...他們應該有消息返回一個所有錯誤字符串不是一個數組,並應該已經提出了一個新的方法來獲得一個數組消息......或者沿着這些線路。 – prodigitalson

1

如果您看看GoCardless_ApiException類代碼,你會發現有一個getResponse()方法可以用來訪問呃響應數組的ror元素...

$try{ 
    $confirmed_resource = GoCardless::confirm_resource($confirm_params); 
}catch(GoCardless_ApiException $e){ 
    $err = 1; 
    $response = $e->getResponse(); 

    print '<h2>Payment Error</h2> 
    <p>Server Returned : <code>' . $response['error'][0] . "</code></p>"; 
}