我正在使用 cURL 构建一个简单的 REST API 包,并希望捕获错误然后返回视图。如果我 dd($e) 我可以抛出错误,但如果我尝试返回一个视图,它只会继续执行 catch 函数之后的代码。 PHP 不应该终止进程并直接进入登录视图吗?
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 客户端,如何捕获该错误并显示身份验证登录视图?
与 Guzzle 不同,如果响应是,Laravel 的 HttpClient 不会抛出错误> 400
.
您应该简单地使用 if 语句来检查响应状态代码。看:https://laravel.com/docs/8.x/http-client#error-handling 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.',
]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)