Custom Error Handling

You can overwrite the error handling for each request by binding your own instance of a class that implements the ErrorHandlerInterface.

The default handler looks like this:

use Illuminate\Http\Client\Response;

class Handler implements ErrorHandlerInterface
{
    public function handle(Response $response)
    {
        if ($response->successful()) {
            return;
        }

        if ($response->status() === 429) {
            throw new TooManyRequestsException($response);
        }

        if ($response->status() === 422) {
            throw new ValidationException($response->json('errors', []));
        }

        if ($response->status() === 404) {
            throw new NotFoundException();
        }

        $response->throw();
    }
}

Register the new handler

To replace the existing one, add the following to your AppServiceProvider or a similar provider.

// within the `register` method
$this->app->bind(ErrorHandlerInterface::class, Handler::class);

Last updated