Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dmag's avatar
Level 6

Http Client: throw exception on all requests if fails

All my client's methods use one base url, so I have the following structure:

public function http()
{
    return Http::baseUrl($this->baseUrl);
}

public function getBuildings()
{
    return $this->http()->get('example-endpoint');
}

I want to throw MyCustomRequestExeption if any request fails. Is there a way to throw an exception in base http instead of appending ->throw() to every method after ->get(...) or ->post(...) (I have a lot of methods)?

I've tried playing with Guzzle middleware, but it passes in Psr\Http\Message\ResponseInterface and thus $response->fails(), $response->body() are not available.

protected function http()
{
    return Http::baseUrl($this->apiUrl)
        ->withMiddleware(Middleware::mapResponse(function (ResponseInterface $response) {
            // code
    }));
}
0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@dmag You can try this:

public function http()
{
    return Http::baseUrl($this->baseUrl)
        ->withMiddleware(Middleware::mapResponse(function (ResponseInterface $response) {
            if ($response->status() >= 400) {
                throw new MyCustomRequestException('Request failed with status code ' . $response->status());
            }

            return $response;
        }));
}
1 like
dmag's avatar
Level 6

@tisuchi but body of the response where error message is contained doesn't seem to be available in that. Response.

Please or to participate in this conversation.