Получить сообщение об ошибке с массивом
Я использую версию API GoCardless на PHP для обработки платежей на моем веб-сайте. Однако, когда их 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>';
}
Благодарю.
ОБНОВЛЕНИЕ 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] => Ресурс уже подтвержден))
3 ответа
Я обнаружил проблему, выход из $e->getMessage()
была простая строка, а не массив.
Поэтому я отредактировал файл Request.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>";
}
и страница выводит:
Ошибка платежа
Сервер возвращен: ресурс уже подтвержден
Метод $e->getMessage()
По-видимому, возвращает массив с индексом error, который снова является массивом, который содержит текст сообщения. Если вы спросите меня, это плохой дизайн 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>";
}
Если вы посмотрите на код класса GoCardless_ApiException, вы увидите, что есть метод getResponse(), который вы можете использовать для доступа к элементу error массива ответов...
$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>";
}