FireBlade's avatar

HTTP client error handling not working when localhost is not available

Am unable to catch this request error when no application is available to respond to the request:

try{
            $response = Http::withHeaders([
                'Content-Type' => 'application/json'
            ])
            ->accept('application/json')
            ->post('http://localhost:8088/save',$sendData);
        }catch(\Exception $e) {
            //can't save $sendData for later use
        } 

$sendData is properly formatted so it's can't be the issue. When I switch on the external application responding at localhost:8088, everything works since there's no error.

0 likes
7 replies
aleahy's avatar

Http doesn't throw exceptions unless it is explicitly requested to. You could chain a ->throw() after the post.

->post('http://localhost:8088/save',$sendData)
->throw();

Or check the request failed:

if ($response->failed()) {
   ...
}

You can check the docs for this: https://laravel.com/docs/11.x/http-client#error-handling

FireBlade's avatar

@aleahy So where is the error coming from ? Even without an explicit error request, an error is thrown and the application stops.

aleahy's avatar

Sorry, I misunderstood - I thought you were saying you weren't getting an error when you needed one.

Where does the stack trace say the error is coming from? It would help to know what the error actually is.

FireBlade's avatar

@aleahy [2024-06-10 06:47:21] local.ERROR: cURL error 7: Failed to connect to localhost port 8088: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://localhost:8088/save {"userId":1,"exception":"[object] (Illuminate\\Http\\Client\\ConnectionException(code: 0): cURL error 7: Failed to connect to localhost port 8088: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://localhost:8088/save at /home//src/vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php:855)

FireBlade's avatar

I need to prevent the application throwing an error and handle it gracefully.

FireBlade's avatar
FireBlade
OP
Best Answer
Level 2

This code is working :

	try {
            Http::withHeaders([
                'Content-Type' => 'application/json'
            ])
            ->accept('application/json')
            ->post('http://localhost:8088/save',$sendData);
        } catch (\Exception $e) {
            return;
        }  
aleahy's avatar

@FireBlade Aside from the return statement, how is this different from what you posted at the beginning?

Please or to participate in this conversation.