2013-03-31 58 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>"; 
}