Sam*_*zon 5 php curl laravel laravel-4
在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();
}
Run Code Online (Sandbox Code Playgroud)
Laravel 抓住了这个例外,但我的捕获声明却没有.Guzzle抛出的例外情况是:
GuzzleHttp\Ring\Exception\ConnectException
Run Code Online (Sandbox Code Playgroud)
它在我的第3行脚本中提出,并没有在我的脚本中捕获.你能给我一个方法来捕捉Guzzle例外吗?
我应该表明我已经看过这些帖子,但我没有得到很好的回复: 如何解决cURL错误(7):无法连接到主机? 并 从Guzzle中捕获cURL错误
我遇到了类似的问题,并使用以下方法解决了它。我使用了您的示例并给出了内联注释供您理解。
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());
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
10152 次 |
| 最近记录: |