Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

627
Visualizações
Laravel - Correct way to catch cURL exceception

I am building a simple REST API package using cURL and would like to catch an error and then return a view. I am able to throw an error if I dd($e) but if I try and return a view it just continues with the code after the catch function. Shouldn't PHP kill the process and just go to the login 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');
}

If I get a cURL timeout exception I just want to go back to the login page for now. If I put in a bogus IP address obviously it will timeout after 2 seconds, which is what I am testing.

Using Laravel Http client, how can I catch that error and display the auth login view?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Unlike Guzzle, Laravel's HttpClient does not throw errors if the response is > 400.

You should simply use an if statement to check the response status code. See: https://laravel.com/docs/8.x/http-client#error-handling

You can call use the following checks:

// 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();

So in your case you can simply do something like this:

$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.',
    ]);
}
over 4 years ago · Santiago Trujillo Relatório

0

Could you try this please?

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());
}

And you can show the error on the frontend, like below;

@if(!empty($errorMessage))
  <div class="alert alert-danger"> {{ $errorMessage }}</div>
@endif
over 4 years ago · Santiago Trujillo Relatório

0

It is better if you change your approach in using Laravel's HTTP client,

Move time-intensive tasks - like Http requests - to a job, and run that job in a background queue.

Then, for example, if you wanna use that Http request for authentication, handle your auth logic on that job, don't forget to log and handle exceptions.

afterward, protect your private routes using middlewares and make redirect unauthenticated users to your login page in that middleware.

I hope I could be clear

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda