我有情况,我需要显示异常中捕获的错误,我想在catch()块之外显示或使用该错误 我的代码是
$error;
try {
$customer = \Stripe\Customer::create(array(
"description"=>"Customer",
"source" => $token,
"email" => $email,
"plan" => "armorax"
)
);
$payment = \Stripe\Charge::create(array(
'amount' => $amount,
'currency' => 'usd',
'description' => $_POST['description'],
"customer" => $customer->id
)
);
}
catch(\Stripe\Error\Card $e) {
$body = $e->getJsonBody();
$err = $body['error'];
$error= 'Status is:' . $e->getHttpStatus() . "\n";
//If i use print('Status is:' . $e->getHttpStatus()) then error is get printed here but i don't need to print error here.
}
//SOme HTML CODE I want to show error below but it is not showing here
<div class="alert"><?php echo $error; ?></div>
我想在catch块之外显示$ error,如上例所示,但它没有打印任何错误
请帮忙
答案 0 :(得分:0)
您可以使用全局变量:
$GLOBALS['myError'] = "Status is:" . $e->getHttpStatus() . "\n";
然后:
<div class="alert"><?php echo $GLOBALS['myError']; ?></div>
或者简单地说:
global $error = "Status is:" . $e->getHttpStatus() . "\n";
然后:
<div class="alert"><?php echo $error; ?></div>
了解有关PHP中全局变量和变量范围的更多信息
http://php.net/manual/en/reserved.variables.globals.php
http://php.net/manual/en/language.variables.scope.php
答案 1 :(得分:0)
除了使用全局变量,您还可以为try-catch块之外的异常预定义变量:
$ex = null;
try {
throw new Exception('Exception thrown inside the try-catch block');
} catch (Throwable $ex) {
// Empty catch to save the exception.
}
if (!is_null($ex)) {
echo $ex->getMessage();
}
请注意,变量不是修改作用域所必需的,而是在没有得到PHP通知的情况下调用is_null
。
使用php -a
在本地运行代码。
我使用了7.3.19