2016-06-29 15 views
2

私はlaravelを使用しています。私は呼び出しているさまざまなAPIからの応答を得るために抽象クラスメソッドを設定しました。しかし、API urlが到達不能な場合、例外をスローします。私は何かが足りないことを知っている。どんな助けでも私のために素晴らしいだろう。guzzleから例外をキャッチ

$offers = []; 
    try { 
     $appUrl = parse_url($this->apiUrl); 

     // Call Api using Guzzle 
     $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']); 

     if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate 
     $client->setDefaultOption('verify', false); 

     $request = $client->get('?' . $appUrl['query']); 
     $response = $request->send(); 
     if ($response->getStatusCode() == 200) { 
     $offers = json_decode($response->getBody(), true); 
     } 
    } catch (ClientErrorResponseException $e) { 
     Log::info("Client error :" . $e->getResponse()->getBody(true)); 
    } catch (ServerErrorResponseException $e) { 
     Log::info("Server error" . $e->getResponse()->getBody(true)); 
    } catch (BadResponseException $e) { 
     Log::info("BadResponse error" . $e->getResponse()->getBody(true)); 
    } catch (\Exception $e) { 
     Log::info("Err" . $e->getMessage()); 
    } 

    return $offers; 

答えて

2

あなたはHTTPプロトコルエラー(すなわち、4xxの上の例外をスロー無効にするには、falseに設定しdocument:guzzlehttp client http-error option explain

、例のコードは次のようにする必要がありますオプション'http_errors' => false, でguzzehttpクライアントを設定する必要がありますおよび5xx応答)。 HTTPプロトコルエラーが発生すると、デフォルトで例外がスローされます。

$client->request('GET', '/status/500'); 
// Throws a GuzzleHttp\Exception\ServerException 

$res = $client->request('GET', '/status/500', ['http_errors' => false]); 
echo $res->getStatusCode(); 
// 500 





$this->client = new Client([ 
    'cookies' => true, 
    'headers' => $header_params, 
    'base_uri' => $this->base_url, 
    'http_errors' => false 
]); 

$response = $this->client->request('GET', '/'); 
if ($code = $response->getStatusCode() == 200) { 
    try { 
     // do danger dom things in here 
    }catch (/Exception $e){ 
     //catch 
    } 

} 
0

あなたが使用しているが、official documentationにこれらの例外が存在しないものを例外とがつがつ食うのバージョンを宣言したかわかりません。

場合によっては、GuzzleHttp\Exception\ConnectExceptionが不足している可能性があります。

1

これらの例外は、グーグルでは正式には定義されていません。

これらの例外はAWS SDK for PHPで定義されています。

公式Guzzleについては、次のようにしてください。

use GuzzleHttp\Client; 
use GuzzleHttp\Exception\RequestException; 
use GuzzleHttp\Exception\ClientException; 

.... 
    try { 
     $response = $this->client->request($method, $url, [ 
      'headers'  => $headers, 
      'form_params' => $form_parameters, 
     ]); 
     $body = (string)$response->getBody(); 
    } catch (ClientException $e) { 
     //do some thing here 
    } catch (RequestException $e) { 
     //do some thing here 
     } 
    } catch (\Exception $e) { 
     //do some thing here 
    }