Real-World Example

  • Middleware applied to GraphQL calls for request logging and error tracking
  • A decider closure determines whether errors should be reported to an external service
PendingRequest::macro('withErrorHandling', function (?Closure $closure = null): PendingRequest {
    return $this->withMiddleware(
        Middleware::mapResponse(function (ResponseInterface $response) use ($closure) {
            $body = collect(json_decode($response->getBody()->getContents(), true));
            $response->getBody()->rewind();

            if (!$body->has('data') || $body->has('errors')) {
                if ($closure instanceof Closure && $closure($response, $body) !== true) {
                    return $response;
                }

                throw new GraphQlResponseException($response, $body);
            }

            return $response;
        })
    );
});

← / → navigate · N notes · Esc exit