在 Laravel 8 中捕获 HTTP 客户端错误

Catch HTTP client errors in Laravel 8

如何捕获 HTTP client 抛出的错误(例如超时),以便它不会在 Laraval 调试器(在调试模式下)中抛出 curl 错误,然后您才能执行任何操作避免停止执行的错误?

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

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

    //continue with another mode

相反,我总是收到 Laravel 的 Ignition 错误页面

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

我的代码没有捕获到错误。有没有可能 laravel 调试器总是有优先级并且不能在调试模式下被覆盖?

这几乎可以肯定是命名空间问题。

您需要在文件顶部添加:

use Illuminate\Http\Client\ConnectionException;

或者这样做:

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

否则,您实际上是在尝试在名为 ConnectionExceptioncurrent 命名空间中捕获某些东西(即类似 App\Controllers\ConnectionException 的东西),这些东西永远不会存在.