Guzzle Curl错误未被try catch语句捕获(Laravel)

5
在 Laravel 项目中,我需要调用 API REST 来删除远程数据。
我的问题是,当出现错误时,我的 catch 语句不能捕获 Guzzle 异常。我的代码如下:
try {
    $client = new \GuzzleHttp\Client();
    $request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
    $status = $request->getStatusCode();
} catch (Exception $e) {
    var_dump($e);exit();
}

这个异常被Laravel捕获了,但并没有被我catch语句所捕获。由Guzzle抛出的异常是:

GuzzleHttp\Ring\Exception\ConnectException

我的脚本第3行出现了错误,但是我无法捕获。请问你能告诉我如何捕获Guzzle异常吗?

我需要说明的是,我已经看过这些帖子,但是没有得到好的回复: 如何解决cURL错误(7):无法连接到主机?从Guzzle中捕获cURL错误

5个回答

14

当我使用

\GuzzleHttp\Exception\ConnectException

而不是

\Guzzle\Http\Exception\ConnectException

时,它对我有用。


在我的情况下,我只是错漏了第一个反斜杠。谢谢。 - Tarps

4

我曾经遇到过类似的问题,并通过以下方法解决。我使用了你的例子,并为你提供了内联注释,以便你理解。

try {
    $client = new \GuzzleHttp\Client();
    $request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
    $status = $request->getStatusCode();
    if($status == 200){
        $response = $response->json();

    }else{
        // The server responded with some error. You can throw back your exception
        // to the calling function or decide to handle it here

        throw new \Exception('Failed');
    }

} catch (\Guzzle\Http\Exception\ConnectException $e) {
    //Catch the guzzle connection errors over here.These errors are something 
    // like the connection failed or some other network error

    $response = json_encode((string)$e->getResponse()->getBody());
}

希望这能对你有所帮助!

1
$response = json_encode((string)$e->getResponse()->getBody()); 对我不起作用,请使用:$e->gethandlerContext()['error'] 获取错误消息部分,例如:“无法解析主机:xxxxx”,并使用\GuzzleHttp\Exception\ConnectException,而不是catch(\Guzzle\Http\Exception\ConnectException $e) {。 - Homer

2
也许该异常没有继承自Exception类。您可以尝试如下方式捕获它:
try {
    $client = new \GuzzleHttp\Client();
    $request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
    $status = $request->getStatusCode();
} catch (\GuzzleHttp\Ring\Exception\ConnectException $e) {
    var_dump($e);exit();
} catch (Exception $e) {
    // ...
}

抱歉,但我已经尝试过了。我不知道为什么它不起作用。 - Samuel Dauzon

1

你可能想要捕获根命名空间中的\Exception,可以通过在catch语句中添加反斜杠或使用use Exception语句来实现。


0

更新答案以适应新的Guzzle异常命名空间

try {
    $client = new \GuzzleHttp\Client();
    $request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
    $status = $request->getStatusCode();
} catch (\GuzzleHttp\Exception\ConnectException $e) {
    var_dump($e);exit();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接