Catch HTTP client errors in Laravel 8

Viewed 5025

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?

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.

Related