該賞金過期5天。此問題的答案有資格獲得 50聲望獎勵。 Chad Priddle想引起更多人對這個問題的關注。
我正在使用 cURL 構建一個簡單的 REST API 包,并希望捕獲錯誤,然后回傳帶有錯誤訊息的視圖。我想查看 cURL 回應是否與字串匹配,然后將錯誤拋出到帶有錯誤訊息的登錄視圖。
老路
try{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://" . $this->ip_address",
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => "username=" . $this->username . "&password=" . $this->password,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$error = curl_error($curl);
if($error == 'failed to authenticate'){
throw new \Exception("you just got an error");
}
} catch (\Exception $e){
return view('auth.login', $e->getMessage);
}
}
如果我 dd($e) ,我可以拋出錯誤,但是如果我嘗試回傳一個視圖,它只會在 catch 函式之后繼續執行代碼。PHP 不應該終止行程并直接轉到登錄視圖嗎?
使用 Laravel HTTP 客戶端更新代碼
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 客戶端,如何捕獲該錯誤并顯示身份驗證登錄視圖?
uj5u.com熱心網友回復:
你能試試這個嗎?
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')->with('errorMessage', $e->getMessage());
}
您可以在前端顯示錯誤,如下所示;
@if(!empty($errorMessage))
<div class="alert alert-danger"> {{ $errorMessage }}</div>
@endif
uj5u.com熱心網友回復:
與 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();
因此,在您的情況下,您可以簡單地執行以下操作:
$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.',
]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334670.html
