Ale*_*Per 1 php error-handling laravel guzzle guzzle6
我需要连接到 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');
});
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我需要调用 API,但在 API 关闭的情况下,我会编写 catch 函数。
但现在当 API 关闭并且 API 返回“500 内部错误”时,该函数就会崩溃......
我的问题是为什么 catch 不处理它?
我如何处理错误 - 当 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))
Run Code Online (Sandbox Code Playgroud)
问题是这里的命名空间,而不是:
} catch (GuzzleHttp\Exception\ClientException $e) {
Run Code Online (Sandbox Code Playgroud)
你应该使用:
} catch (\GuzzleHttp\Exception\ClientException $e) {
Run Code Online (Sandbox Code Playgroud)
否则 PHP 假设该类位于当前命名空间中,因此实际上当您使用时GuzzleHttp\Exception\ClientException
实际上您可能使用过App\Http\Controllers\GuzzleHttp\Exception\ClientException
,并且 Guzzle 显然不会抛出此类异常。