[英]How to prevent crashing when Guzzle detect 400 or 500 error?
我正在使用PHP guzzle
我努力了
public static function get($url) {
$client = new Client();
try {
$res = $client->request('GET',$url);
$result = (string) $res->getBody();
$result = json_decode($result, true);
return $result;
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
}
我不斷得到
當Guzzle檢測到400或500錯誤時如何防止崩潰?
我只是希望我的應用程序繼續運行和加載。
所以,我敢打賭你的get()
函數存在於像App\\Http\\Controllers
這樣的命名空間中,這意味着:
catch (GuzzleHttp\Exception\ClientException $e) {
實際上被解釋為好像你寫的:
catch (App\Http\Controllers\GuzzleHttp\Exception\ClientException $e) {
出於顯而易見的原因,拋出這種情況並不例外。
您可以通過執行以下操作來修復命名空間問題:
catch (\GuzzleHttp\Exception\ClientException $e) {
(注意領先\\
)或推桿:
use GuzzleHttp\Exception\ClientException;
在namespace
聲明之后的文件頂部,只捕獲ClientException
。
請參見http://php.net/manual/en/language.namespaces.basics.php 。
我會嘗試這樣的事情:
public static function get($url) {
try {
$client = new Client();
$res = $client->request('GET',$url);
$result = (string) $res->getBody();
$result = json_decode($result, true);
return $result;
}
catch (\Exception $e) {
if($e instanceof \GuzzleHttp\Exception\ClientException ){
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
report($e);
return false;
}
}
report()
輔助函數允許您使用異常處理程序的報告方法快速報告異常,而無需呈現錯誤頁面。
另外,請查看http_errors
選項以完全禁用異常(如果您的應用程序是預期的情況,並且您希望自己專門處理所有響應)。
而不是只使用ClientException
您可以嘗試RequestException ,這將有助於處理錯誤的請求。
try {
// Your code here.
} catch (GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
// Get response body
// Modify message as proper response
$message = $e->getResponse()->getBody();
return (string) $exception;
}
else {
return $e->getMessage();
}
}
您可以通過以下方式捕獲任何異常:
catch (\Exception $e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.