gpt4 book ai didi

php - 如何使用Laravel在Controller中捕获500错误

转载 作者:行者123 更新时间:2023-12-03 08:05:04 24 4
gpt4 key购买 nike

我需要连接到API,所以我编写了一个函数:

try {
$res4 = $client3->post('https://api.example.co.uk/Book', [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ajhsdbjhasdbasdbasd',
],
'json' => [
'custFirstName' => $FirstName,
'custLastName' => $Surname,
'custPhone' => $Mobile,
'custEmail' => $Email,
]
]);
} catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
$item->update(['status' => 'Problems at step3']);
Mail::raw('Problem at STEP 3', function ($message) use ($serial) {
$message->from('asd.asd@gmail.com', 'asd.asd@gmail.com');
$message->subject('We got a problem etc.');
$message->to('john.smith@gmail.com');
});
}

如您所见,我需要调用API,但是在API中断的情况下,我会编写catch函数。

但是现在,当API关闭并且API返回“500 Internal Error”时,此函数就崩溃了...

我的问题是为什么不捕获它?

我如何处理错误-当API中断或请求错误时...为什么catch {}不起作用?

更新:这是我的laravel.log
[2018-10-25 14:51:04] local.ERROR: GuzzleHttp\Exception\ServerException: Server error: `POST https://api.example.co.uk/Book` resulted in a `500 Internal Server Error` response:
{"message":"An error has occured. Please contact support."}
in /home/public_html/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
Stack trace:
#0 /home/public_html/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /home/public_html/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))

最佳答案

问题是这里的 namespace ,而不是:

} catch (GuzzleHttp\Exception\ClientException $e) {

您应该使用:
} catch (\GuzzleHttp\Exception\ClientException $e) {

否则,PHP会假定该类在当前的 namespace 中,因此实际上,当您使用 GuzzleHttp\Exception\ClientException时,实际上您可能使用了 App\Http\Controllers\GuzzleHttp\Exception\ClientException,并且此类异常显然不会被Guzzle抛出。

关于php - 如何使用Laravel在Controller中捕获500错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52992096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com