从guzzle中抓住异常

时间:2016-06-29 08:55:10

标签: php laravel-5 exception-handling guzzle

我正在使用laravel,我已经设置了抽象类方法,以便从我调用的各种API中获取响应。但是如果API网址无法访问,则会抛出异常。我知道我错过了什么。任何帮助对我来说都很棒。

$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;

4 个答案:

答案 0 :(得分:3)

您应该使用选项 'http_errors' => false, 设置guzzehttp客户端 示例代码应该是这样的,document:guzzlehttp client http-error option explain

  

设置为false以禁用在HTTP协议错误(即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
   }

}

答案 1 :(得分:1)

这些例外并未在guzzle中正式定义。

这些例外情况在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
    }

答案 2 :(得分:0)

您可以创建自己的例外

Class CustomException扩展了Exception { }

接下来,您将抽象类的异常抛出您自己的异常

catch(ConnectException $ConnectException)
    {
        throw new CustomException("Api excception ConnectException",1001);

    }

然后处理全局异常处理程序渲染方法

 if($exception instanceof CustomException)
       {

          dd($exception);

       }

答案 3 :(得分:-1)

不确定您是如何声明这些例外以及您使用的是哪个Guzzle版本,但在official documentation中这些例外不存在。

在您的情况下,您可能会遗漏import requests from requests_toolbelt import MultipartEncoder url = 'http://example.com/example/asdfas' fields = {'value_1':'12345', 'value_2': '67890'} data = MultipartEncoder(fields=fields) headers["Content-type"] = m.content_type requests.post(url=url, data=data, headers=headers)