blog.iwanluijks.nl
IL
Blog post

Pushing GraphQL errors from API Platform to Sentry

By Iwan Luijks · · Back to blog


By default errors resulting from GraphQL calls done to API Platform don't end up in Sentry. Use the following piece of code and configuration to make sure they will be send to Sentry.

<?php
declare(strict_types=1);

namespace MyNamespace;

use ApiPlatform\GraphQl\Error\ErrorHandlerInterface;
use GraphQL\Error\Error;
use Sentry\State\HubInterface;

class ErrorHandler implements ErrorHandlerInterface
{
    public function __construct(
        private ErrorHandlerInterface $defaultErrorHandler,
        private ?HubInterface $sentryHub = null
    )
    {
    }

    /**
     * @param Error[] $errors
     */
    public function __invoke(array $errors, $formatter): array
    {
        if ($this->sentryHub) {
            array_map(fn(Error $error) => $this->sentryHub->captureException($error), $errors);
        }

        return ($this->defaultErrorHandler)($errors, $formatter);
    }
}

Add the configuration below to your services configuration making sure this error handler is picked up as the main API Platform error handler.

MyNamespace\ErrorHandler:
    decorates: api_platform.graphql.error_handler

This article was updated on . Labeled under: sentry, php, apiplatform.