ProgramingTip

Guzzle에서 예외 잡기

bestdevel 2020. 11. 9. 20:27
반응형

Guzzle에서 예외 잡기


API에서 실행중인 개발 테스트에서 Guzzle을 사용하여 API 메서드를 사용하고 있습니다. try / catch 블록에 래핑 된 테스트가 여전히 처리되지 않는 예외 오류가 발생합니다. 문서에 설명 된대로 이벤트 리스너를 추가해도 아무 작업도 수행되지 않는 것입니다. HTTP 코드가 500, 401, 400 인 응답을 검색해야합니다. 실제로 작동하지 않는 경우 시스템이 호출 결과에 따라 가장 적절한 코드를 설정하여 200이 아닌 모든 코드를 검색 할 수 있습니다. .

현재 코드 예

foreach($tests as $test){

        $client = new Client($api_url);
        $client->getEventDispatcher()->addListener('request.error', function(Event $event) {        

            if ($event['response']->getStatusCode() == 401) {
                $newResponse = new Response($event['response']->getStatusCode());
                $event['response'] = $newResponse;
                $event->stopPropagation();
            }            
        });

        try {

            $client->setDefaultOption('query', $query_string);
            $request = $client->get($api_version . $test['method'], array(), isset($test['query'])?$test['query']:array());


          // Do something with Guzzle.
            $response = $request->send();   
            displayTest($request, $response);
        }
        catch (Guzzle\Http\Exception\ClientErrorResponseException $e) {

            $req = $e->getRequest();
            $resp =$e->getResponse();
            displayTest($req,$resp);
        }
        catch (Guzzle\Http\Exception\ServerErrorResponseException $e) {

            $req = $e->getRequest();
            $resp =$e->getResponse();
            displayTest($req,$resp);
        }
        catch (Guzzle\Http\Exception\BadResponseException $e) {

            $req = $e->getRequest();
            $resp =$e->getResponse();
            displayTest($req,$resp);
        }
        catch( Exception $e){
            echo "AGH!";
        }

        unset($client);
        $client=null;

    }

일시적인 예외 유형에 대한 특정 특정 블록이 있어도 여전히 돌아오고 있습니다.

Fatal error: Uncaught exception 'Guzzle\Http\Exception\ClientErrorResponseException' with message 'Client error response [status code] 401 [reason phrase] Unauthorized [url]

예상대로 페이지의 모든 실행이 중지됩니다. BadResponseException catch를 추가하여 404를 잡을 수 있지만 500 또는 401 응답에 작동하지 않는 것입니다. 누구든지 내가 어디로 잘못 가고 있는지 제안 할 수 있습니까?


해당 try블록 에서 예외가 발생하면 최악의 시나리오에서 Exception잡히지 않은 모든 것이 발생합니다.

테스트의 첫 번째 부분이 예외를 던지고이를 try블록에 래핑하는 것임을 고려하십시오 .


프로젝트에 따라 예외를 취소해야 할 수도 있습니다. 코딩 규칙이 흐름 제어에 대한 예외를 허용하지 않습니다. 다음 과 같이 Guzzle 3에 대한 예외 제외하고 할 수 있습니다 .

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

이제 모든 상태 코드를 쉽게 사용할 수 있습니다.

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

확인하고 유효한 코드가 있으면 다음과 같이 사용할 수 있습니다.

if ($statuscode > 300) {
  // Do some error handling
}

... 또는 모든 예상 코드를 더 잘 처리합니다.

if (200 === $statuscode) {
  // Do something
}
elseif (304 === $statuscode) {
  // Nothing to do
}
elseif (404 === $statuscode) {
  // Clean up DB or something like this
}
else {
  throw new MyException("Invalid response from api...");
}

Guzzle 5.3 용

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

@mika 덕분에

Guzzle 6 용

$client = new \GuzzleHttp\Client(['http_errors' => false]);

Guzzle 오류를 잡으려면 다음과 같이 할 수 있습니다.

try {
    $response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
    echo 'Uh oh! ' . $e->getMessage();
}

... 그러나 요청을 "로그"하거나 "재전송"다음과 같이 시도하십시오.

// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
    'request.error', 
    function(Event $event) {

        //write log here ...

        if ($event['response']->getStatusCode() == 401) {

            // create new token and resend your request...
            $newRequest = $event['request']->clone();
            $newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
            $newResponse = $newRequest->send();

            // Set the response object of the request without firing more events
            $event['response'] = $newResponse;

            // You can also change the response and fire the normal chain of
            // events by calling $event['request']->setResponse($newResponse);

            // Stop other events from firing when you override 401 responses
            $event->stopPropagation();
        }

});

... 또는 "이벤트 전파를 중지"예측 이벤트 리스너 (-255보다 높은 우선 순위)를 재정의하고 이벤트 전파를 중지 할 수 있습니다.

$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
        // Stop other events from firing when you get stytus-code != 200
        $event->stopPropagation();
    }
});

다음과 같은 guzzle 오류를 방지하는 것이 좋습니다.

request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response

귀하의 응용 프로그램에서.


제 경우 Exception에는 네임 스페이스 파일을 던지고 있었기 때문에 PHP는 My\Namespace\Exception예외를 전혀 없었습니다.

catch (Exception $e)올바른 Exception클래스를 찾는 지 확인할 가치 있습니다.

그냥 시도 catch (\Exception $e)(그와 \함께이)하고 작동 확인합니다.


http_errors => false로 추가 매개 변수를 추가해야합니다.

$request = $client->get($url, ['http_errors' => false]);

오래된 질문이지만 Guzzle은 예외 객체 내에 응답을 추가합니다. 그래서 간단한 try-catch를 GuzzleHttp\Exception\ClientException한 다음 getResponse해당 예외를 사용하여 400 레벨 오류를 확인하고 거기에서 계속하십시오.


내가 잡기되었다 GuzzleHttp\Exception\BadResponseException@dado이 제안되어있다. 하지만 어느 날 GuzzleHttp\Exception\ConnectException도메인에 대한 DNS를 사용할 수 없었습니다. 그래서 제 제안은 GuzzleHttp\Exception\ConnectExceptionDNS 오류에 대해서도 안전을 확보하는 것입니다.

참고 URL : https://stackoverflow.com/questions/17658283/catching-exceptions-from-guzzle

반응형