我正在使用 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');
}
Run Code Online (Sandbox Code Playgroud)
如果我遇到 cURL 超时异常,我现在只想返回登录页面。如果我输入一个伪造的IP地址,显然它会在2秒后超时,这就是我正在测试的。
使用 Laravel Http 客户端,如何捕获该错误并显示身份验证登录视图?
与 Guzzle 不同,如果响应为 ,Laravel 的 HttpClient 不会抛出错误> 400。
您应该简单地使用 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();
Run Code Online (Sandbox Code Playgroud)
因此,在您的情况下,您可以简单地执行以下操作:
$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.',
]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7449 次 |
| 最近记录: |