4

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?

shaedrich
  • 5,457
  • 3
  • 26
  • 42
Sandro Antonucci
  • 1,683
  • 5
  • 29
  • 59

1 Answers1

6

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.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • Hi, only the second method works but I would prefer the first, do you know why? – Sandro Antonucci Nov 16 '20 at 18:46
  • No; I'd suspect you made a mistake somewhere (typo?) if that's the case. – ceejayoz Nov 16 '20 at 19:14
  • Although I am on Laravel 9, in my case both of them fail... :( I see `local.ERROR: cURL error 6: Could not resolve host:` and my `catch` block not working... Any pointers would be much appreciated. Thanks. – burf Aug 17 '22 at 08:28