2017-09-01 512 views
0

即时通讯尝试处理请求状态码,基本上检查状态是否为200,以防处理它。即时通讯使用一个名为“GuzzleHttp \客户端”包,当有404它给了我一个错误:处理GuzzleHttp上的客户端错误异常

Client error: `GET https://api.someurl---` resulted in a `404 Not Found` response: 
{"generated_at":"2017-09-01T16:59:25+00:00","schema":"","message":"No events scheduled for this date."} 

但比在屏幕中显示为,我想改变格式,所以我尝试赶上并在视图上给出不同的输出。但没有工作,它仍然给我的红色屏幕错误。

try { 
      $client = new \GuzzleHttp\Client(); 
      $request = $client->request('GET', $url); 
      $status = $request->getStatusCode(); 
      if($status == 200){ 
       return $status; 

      }else{ 

       throw new \Exception('Failed'); 
      } 

     } catch (\GuzzleHttp\Exception\ConnectException $e) { 
      //Catch errors 
      return $e->getStatusCode(); 

     } 
+0

所以你试图从你的guzzle请求或仅仅是一个连接异常中捕获404异常? – JLeggatt

+0

即时尝试检查404或其他状态代码,如200 –

回答

0

好了,如果你要坚持你想要做这样的事情一个try-catch:

$client = new \GuzzleHttp\Client(); 

try { 
    $request = $client->request('GET', $url); 
} catch (\GuzzleHttp\Exception\ConnectException $e) { 
    // This is will catch all connection timeouts 
    // Handle accordinly 
} catch (\GuzzleHttp\Exception\ClientException $e) { 
    // This will catch all 400 level errors. 
    return $e->getResponse()->getStatusCode(); 
} 

$status = $request->getStatusCode(); 

如果抓不被触发的$request会成功意味着它”将有一个200的状态代码。 但是,要设置$client,要捕捉400错误,请确保已将http_errors请求选项设置为true。