在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):could dn't connect to host?和从Guzzle捕获cURL错误
当我使用
不是' GuzzleHttp '例外' ConnectException
'狂饮' Http异常' ' ConnectException
我有一个类似的问题,并使用以下内容解决了它。我已经使用了您的示例并给出了内联注释,以便您理解。
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());
}
希望这对你有帮助!
也许这个例外并没有扩展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) {
// ...
}
您的意思可能是捕获'Exception
(在根命名空间中),通过在catch语句中添加反斜杠或use Exception
语句。
Just将答案更新到新的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();
}