gpt4 book ai didi

php - Laravel - 捕获 cURL 异常的正确方法

转载 作者:行者123 更新时间:2023-12-04 13:05:31 25 4
gpt4 key购买 nike

我正在使用 cURL 构建一个简单的 REST API 包,并希望捕获错误然后返回一个 View 。如果我 dd($e) ,我可以抛出一个错误,但是如果我尝试返回一个 View ,它只会在 catch 函数之后继续执行代码。 PHP 不应该终止进程并直接转到登录 View 吗?

try{    
$response = Http::timeout(2)->asForm()->post('https://' . $this->ip_address, [
'username' => $this->username,
'password' => $this->password
]);

} catch(\Illuminate\Http\Client\ConnectionException $e) {
return view('auth.login');
}
如果我收到 cURL 超时异常,我现在只想返回登录页面。如果我输入一个虚假的 IP 地址,它会在 2 秒后超时,这就是我正在测试的。
使用 Laravel Http 客户端,如何捕获该错误并显示身份验证登录 View ?

最佳答案

与 Guzzle 不同的是,如果响应是 > 400,Laravel 的 HttpClient 不会抛出错误。 .
您应该简单地使用 if 语句来检查响应状态代码。见:https://laravel.com/docs/8.x/http-client#error-handling
您可以调用使用以下检查:

// Determine if the status code is >= 200 and < 300...
$response->successful();

// Determine if the status code is >= 400...
$response->failed();

// Determine if the response has a 400 level status code...
$response->clientError();

// Determine if the response has a 500 level status code...
$response->serverError();
因此,在您的情况下,您可以简单地执行以下操作:
$response = Http::timeout(2)->asForm()->post('https://' . $this->ip_address, [
'username' => $this->username,
'password' => $this->password
]);

if ($response->failed()) {
return view('your-view')->with([
'message' => 'Failed.',
]);
}

关于php - Laravel - 捕获 cURL 异常的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69649975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com