Skip to content

Commit

Permalink
Merge pull request #47 from TomHAnderson/hotfix/catch-graphql-exception
Browse files Browse the repository at this point in the history
Catch graphql exception
  • Loading branch information
TomHAnderson authored Sep 16, 2024
2 parents fb00d0c + 7a2863e commit 65da90e
Showing 1 changed file with 28 additions and 18 deletions.
46 changes: 28 additions & 18 deletions app/Http/Controllers/GraphQLController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use ApiSkeletons\Doctrine\ORM\GraphQL\Config;
use ApiSkeletons\Doctrine\ORM\GraphQL\Driver;
use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem;
use App\GraphQL\Mutation;
use App\GraphQL\Query;
use Doctrine\Laminas\Hydrator\DoctrineObject;
Expand All @@ -18,6 +19,7 @@
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\QueryComplexity;
use Illuminate\Http\Request;
use Throwable;

use function array_map;
use function config;
Expand All @@ -31,6 +33,10 @@ public function __invoke(EntityManager $entityManager, Request $request): array
$variables = $request->json('variables') ?? [];
$operationName = $request->json('operationName');

if (! $query) {
return ApiProblem::response('Query is required', 422);
}

$context = [];

$driver = new Driver($entityManager, new Config([
Expand Down Expand Up @@ -65,26 +71,30 @@ public function __invoke(EntityManager $entityManager, Request $request): array
// Limit query complexity
DocumentValidator::addRule(new QueryComplexity(350));

// Execute
$result = GraphQL::executeQuery(
schema: $schema,
source: (string) $query,
contextValue: $context,
variableValues: $variables,
operationName: $operationName,
)
->setErrorFormatter(static function (Error $error): array {
$exception = $error->getPrevious() ?: $error;
try {
// Execute
$result = GraphQL::executeQuery(
schema: $schema,
source: (string) $query,
contextValue: $context,
variableValues: $variables,
operationName: $operationName,
)
->setErrorFormatter(static function (Error $error): array {
$exception = $error->getPrevious() ?: $error;

// Local development
if (config('app.debug')) {
throw $exception;
}
// Local development
if (config('app.debug')) {
throw $exception;
}

return FormattedError::createFromException($error);
})
->setErrorsHandler(static fn (array $errors, callable $formatter): array => array_map($formatter, $errors));
return FormattedError::createFromException($error);
})
->setErrorsHandler(static fn (array $errors, callable $formatter): array => array_map($formatter, $errors));

return $result->toArray();
return $result->toArray();
} catch (Throwable $e) {
return FormattedError::createFromException($e);
}
}
}

0 comments on commit 65da90e

Please sign in to comment.