在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行中引发,但没有被我的脚本捕获。您能给我一种方法来捕捉“枪口例外”吗?
我应该指出我已经看过这些帖子,但是没有得到很好的答复:如何解决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());
}
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句