使用Try/Catch PHP方法捕获条带错误

sam*_*yb8 41 php error-handling try-catch stripe-payments

在网站上测试STRIPE期间,我构建了这样的代码:

   try {
        $charge = Stripe_Charge::create(array(
          "amount" => $clientPriceStripe, // amount in cents
          "currency" => "usd",
          "customer" => $customer->id,
          "description" => $description));
          $success = 1;
          $paymentProcessor="Credit card (www.stripe.com)";
    } 
    catch (Stripe_InvalidRequestError $a) {
        // Since it's a decline, Stripe_CardError will be caught
        $error3 = $a->getMessage();
    }

    catch (Stripe_Error $e) {
        // Since it's a decline, Stripe_CardError will be caught
        $error2 = $e->getMessage();
        $error = 1;
    }
if ($success!=1)
{
    $_SESSION['error3'] = $error3;
    $_SESSION['error2'] = $error2;
    header('Location: checkout.php');
    exit();
}
Run Code Online (Sandbox Code Playgroud)

问题是卡有时会出错(没有被我在那里的"catch"参数捕获)并且"try"失败并且页面立即在屏幕上发布错误而不是进入"if"和重定向回checkout.php.

我应该如何构建我的错误处理,以便我收到错误并立即重定向回checkout.php并在那里显示错误?

谢谢!


抛出错误:

Fatal error: Uncaught exception 'Stripe_CardError' with message 'Your card was declined.' in ............
/lib/Stripe/ApiRequestor.php on line 92
Run Code Online (Sandbox Code Playgroud)

lee*_*ers 99

如果您正在使用Stripe PHP库并且它们已被命名空间(例如,当它们通过Composer安装时),您可以捕获所有Stripe异常:

<?php 
try {
  // Use a Stripe PHP library method that may throw an exception....
  \Stripe\Customer::create($args);
} catch (\Stripe\Error\Base $e) {
  // Code to do something with the $e exception object when an error occurs
  echo($e->getMessage());
} catch (Exception $e) {
  // Catch any other non-Stripe exceptions
}
Run Code Online (Sandbox Code Playgroud)

  • @Ryan所有Stripe错误类都继承自`Stripe\Error\Base`,第一个`catch`块将匹配所有这些子类.我添加了第二个更强大的`catch`,并处理Stripe API调用不返回Stripe异常的情况. (4认同)
  • 请参阅另一个答案(http://stackoverflow.com/a/17750537/470749),它指的是条纹文档(https://stripe.com/docs/api?lang=php#errors),它们显示了不同的要捕获的错误对象.`Stripe\Error\Base`是不够的. (2认同)

Ogu*_*zel 58

我认为要捕获的不仅仅是这些异常(Stripe_InvalidRequestErrorStripe_Error).

以下代码来自Stripe的网站.可能会发生这些您未考虑的其他异常,并且您的代码有时会失败.

try {
  // Use Stripe's bindings...
} catch(Stripe_CardError $e) {
  // Since it's a decline, Stripe_CardError will be caught
  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "\n");
  print('Type is:' . $err['type'] . "\n");
  print('Code is:' . $err['code'] . "\n");
  // param is '' in this case
  print('Param is:' . $err['param'] . "\n");
  print('Message is:' . $err['message'] . "\n");
} catch (Stripe_InvalidRequestError $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
  // Network communication with Stripe failed
} catch (Stripe_Error $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
}
Run Code Online (Sandbox Code Playgroud)

编辑:

try {
    $charge = Stripe_Charge::create(array(
    "amount" => $clientPriceStripe, // amount in cents
    "currency" => "usd",
    "customer" => $customer->id,
    "description" => $description));
    $success = 1;
    $paymentProcessor="Credit card (www.stripe.com)";
} catch(Stripe_CardError $e) {
  $error1 = $e->getMessage();
} catch (Stripe_InvalidRequestError $e) {
  // Invalid parameters were supplied to Stripe's API
  $error2 = $e->getMessage();
} catch (Stripe_AuthenticationError $e) {
  // Authentication with Stripe's API failed
  $error3 = $e->getMessage();
} catch (Stripe_ApiConnectionError $e) {
  // Network communication with Stripe failed
  $error4 = $e->getMessage();
} catch (Stripe_Error $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
  $error5 = $e->getMessage();
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
  $error6 = $e->getMessage();
}

if ($success!=1)
{
    $_SESSION['error1'] = $error1;
    $_SESSION['error2'] = $error2;
    $_SESSION['error3'] = $error3;
    $_SESSION['error4'] = $error4;
    $_SESSION['error5'] = $error5;
    $_SESSION['error6'] = $error6;
    header('Location: checkout.php');
    exit();
}
Run Code Online (Sandbox Code Playgroud)

现在,您将捕获所有可能的异常,并且可以根据需要显示错误消息.而且$ error6适用于不相关的例外.

  • 问题是代码通过了 ApiRequestor.php(Stripe 的文件)并且在那里失败了并且没有继续通过我的“捕获” (2认同)
  • 在另一种情况下,你设置然后检查$ success并根据结果重定向的技术对我来说是一个很大的帮助.谢谢! (2认同)

小智 11

我可能会迟到这个问题,但我遇到了同样的问题并发现了这个问题.

您只需要使用"Stripe_Error"类.

use Stripe_Error;
Run Code Online (Sandbox Code Playgroud)

在宣布之后,我能够成功捕获错误.


Dja*_*ave 8

这是对另一个答案的更新,但是文档已经略有改变,因此我使用以下方法取得了成功:

try {
  // Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
  // Since it's a decline, \Stripe\Error\Card will be caught
  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "\n");
  print('Type is:' . $err['type'] . "\n");
  print('Code is:' . $err['code'] . "\n");
  // param is '' in this case
  print('Param is:' . $err['param'] . "\n");
  print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\RateLimit $e) {
  // Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
  // Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
}
Run Code Online (Sandbox Code Playgroud)

您可以在Stripe文档中找到此源代码:

https://stripe.com/docs/api?lang=php#handling-errors


xin*_*ose 6

这是Stripe在2017年捕获错误的方式. 文档.此代码段需要PHP 7.1+

try {
    // make Stripe API calls
} catch(\Stripe\Exception\ApiErrorException $e) {
    $return_array = [
        "status" => $e->getHttpStatus(),
        "type" => $e->getError()->type,
        "code" => $e->getError()->code,
        "param" => $e->getError()->param,
        "message" => $e->getError()->message,
    ];
    $return_str = json_encode($return_array);          
    http_response_code($e->getHttpStatus());
    echo $return_str;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下代码捕获ajax中的错误:

$(document).ajaxError(function ajaxError(event, jqXHR, ajaxSettings, thrownError) {
    try {
        var url = ajaxSettings.url;
        var http_status_code = jqXHR.status;
        var response = jqXHR.responseText;
        var message = "";
        if (isJson(response)) {     // see here for function: https://stackoverflow.com/a/32278428/4056146
            message = "  " + (JSON.parse(response)).message;
        }
        var error_str = "";

        // 1. handle HTTP status code
        switch (http_status_code) {
            case 0: {
                error_str = "No Connection.  Cannot connect to " + new URL(url).hostname + ".";
                break;
            }   // No Connection
            case 400: {
                error_str = "Bad Request." + message + "  Please see help.";
                break;
            }   // Bad Request
            case 401: {
                error_str = "Unauthorized." + message + "  Please see help.";
                break;
            }   // Unauthorized
            case 402: {
                error_str = "Request Failed." + message;
                break;
            }   // Request Failed
            case 404: {
                error_str = "Not Found." + message + "  Please see help.";
                break;
            }   // Not Found
            case 405: {
                error_str = "Method Not Allowed." + message + "  Please see help.";
                break;
            }   // Method Not Allowed
            case 409: {
                error_str = "Conflict." + message + "  Please see help.";
                break;
            }   // Conflict
            case 429: {
                error_str = "Too Many Requests." + message + "  Please try again later.";
                break;
            }   // Too Many Requests
            case 500: {
                error_str = "Internal Server Error." + message + "  Please see help.";
                break;
            }   // Internal Server Error
            case 502: {
                error_str = "Bad Gateway." + message + "  Please see help.";
                break;
            }   // Bad Gateway
            case 503: {
                error_str = "Service Unavailable." + message + "  Please see help.";
                break;
            }   // Service Unavailable
            case 504: {
                error_str = "Gateway Timeout." + message + "  Please see help.";
                break;
            }   // Gateway Timeout
            default: {
                console.error(loc + "http_status_code unhandled >> http_status_code = " + http_status_code);
                error_str = "Unknown Error." + message + "  Please see help.";
                break;
            }
        }

        // 2. show popup
        alert(error_str);
        console.error(arguments.callee.name + " >> http_status_code = " + http_status_code.toString() + "; thrownError = " + thrownError + "; URL = " + url + "; Response = " + response);

    }
    catch (e) {
        console.error(arguments.callee.name + " >> ERROR >> " + e.toString());
        alert("Internal Error.  Please see help.");
    }
});
Run Code Online (Sandbox Code Playgroud)