2017-10-18 4 views
3

난 내가 Guzzle이 400 또는 500 오류를 감지하면 충돌을 방지하는 방법은 무엇입니까?

enter image description here

어떻게 목구멍이 400 또는 500 오류가 detecct 때 충돌 방지

을 받고 유지

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(); 
    } 

} 

을 시도

을 목구멍 PHP 사용하고 있습니다?

방금 ​​내 응용 프로그램을 계속 실행하고로드하려고합니다.

catch (GuzzleHttp\Exception\ClientException $e) { 

당신이 작성했던 것처럼 실제로해석되고있다 :

+1

'catch (\ GuzzleHttp \ Exception \ ClientException $ e)'를 시도하거나 다른 네임 스페이스 지침과 함께 파일 상단에'Use GuzzleHttp \ Exception \ ClientException; '를 넣으십시오. – ceejayoz

+0

10k'er 및 [들여 쓰기가 필요 했습니까?] (https://stackoverflow.com/revisions/46817723/2) * lol * –

+0

코드는 어디에 있습니까? 죄송합니다. 나는 의미하지 않았다. – ihue

답변

4

그래서, 나는 당신의 get() 기능이 의미 App\Http\Controllers 같은 공간에 존재 셨을 텐데요

catch (App\Http\Controllers\GuzzleHttp\Exception\ClientException $e) { 

명백한 이유로, 그런 종류의 예외는 없습니다.

당신은 수행하여 네임 스페이스 지정 문제를 해결할 수 있습니다 :

use GuzzleHttp\Exception\ClientException; 

namespace 선언 후 파일의 맨 위에 잡는 단지 ClientException :

catch (\GuzzleHttp\Exception\ClientException $e) { 

또는 퍼팅합니다 (\를 선도주의) .

http://php.net/manual/en/language.namespaces.basics.php을 참조하십시오.

당신이 어떤 예외를 잡을 수
+2

그리고 OP가 4xx 또는 5xx 임에도 불구하고 OP를 본문으로 되돌리려는 경우 OP에서 Guzzle의 [http_errors 설정]을 사용할 수 있습니다 (http : // docs .guzzlephp.org/ko/stable/request-options.html # http-errors). – bishop

0

:

catch (\Exception $e) 
1

내가 이런 식으로 뭔가를 시도 할 것입니다 :

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() 도우미 기능을 사용하면 신속하게 예외 핸들러의보고 방법을 사용하여 예외를보고 할 수 있습니다를 오류 페이지를 렌더링하지 않아도됩니다.

1

예외를 전혀 사용하지 않으려면 http_errors 옵션을 사용하십시오 (응용 프로그램의 경우 예상되는 시나리오이고 사용자가 구체적으로 모든 응답을 처리하려는 경우).