Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch HTTP client errors in Laravel 8

How do you catch errors thrown by the HTTP client (for example a time out) so that it doesn't throw the curl error in the Laraval debugger (in debug mode) before you can do anything with the error to avoid stopping the execution?

    use Illuminate\Support\Facades\Http;
    try {
        $request = Http::post('https://example.com/post', [
        'password' => 'guest']);

    } catch(ConnectException $e)
    {
        //log error
    }

    //continue with another mode

Instead, I'm always getting the Laravel's Ignition error page

Illuminate\Http\Client\ConnectionException
cURL error 28: Failed to connect to example.com port 443: Timed out

and the error is not caught by my code. Is it possible that the laravel debugger always have priority and can't be overridden in debug mode?

like image 667
Sandro Antonucci Avatar asked Oct 21 '25 09:10

Sandro Antonucci


1 Answers

This is almost certainly a namespacing issue.

You'll need either this at the top of the file:

use Illuminate\Http\Client\ConnectionException;

or do this:

} catch(\Illuminate\Http\Client\ConnectionException $e)

Otherwise, you're actually trying to catch something in the current namespace named ConnectionException (i.e. something like App\Controllers\ConnectionException), which will never exist.

like image 143
ceejayoz Avatar answered Oct 23 '25 22:10

ceejayoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!