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.
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;
}));
}