Laravel - HTTP Client - Throwing Exceptions

If you have a response instance and would like to throw an instance of Illuminate\Http\Client\RequestException if the response status code indicates a client or server error, you may use the throw or throwIf methods:

    
    $response = Http::post(...);
    
    // Throw an exception if a client or server error occurred...
    $response->throw();
    
    // Throw an exception if an error occurred and the given condition is true...
    $response->throwIf($condition);
    
    return $response['user']['id'];
	

The Illuminate\Http\Client\RequestException instance has a public $response property which will allow you to inspect the returned response.

The throw method returns the response instance if no error occurred, allowing you to chain other operations onto the throw method:

    
    return Http::post(...)->throw()->json();
	

If you would like to perform some additional logic before the exception is thrown, you may pass a closure to the throw method. The exception will be thrown automatically after the closure is invoked, so you do not need to re-throw the exception from within the closure:

    
    return Http::post(...)->throw(function ($response, $e) {
        //
    })->json();