2016-06-29 4 views
2

저는 laravel을 사용하고 있습니다. 저는 다양한 API에서 응답을 얻기 위해 추상 클래스 메소드를 설정했습니다. 그러나 API url에 도달 할 수없는 경우 예외가 발생합니다. 나는 뭔가를 놓친다는 것을 안다. 어떤 도움이 나를 위해 위대한 것입니다.놀이터에서 예외 잡기

$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_errors' => false, 예제 코드는 다음과 같이해야 false로 document:guzzlehttp client http-error option explain

설정은 HTTP 프로토콜 오류에 예외를 던지는 해제하는 옵션과 함께 guzzehttp 클라이언트를 설정해야합니다 (즉, 4XX 및 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 
    }