-
-
Notifications
You must be signed in to change notification settings - Fork 565
Multiple errors from one resolver #207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
If this is not supported, please give me some tips how to implement it and I'll send a PR. |
You have at least couple options:
'resolve' => function($_, $args) {
$errors = [];
if (empty($args['name'])) {
$errors[] = 'Name could not be empty';
}
if ($args['age'] < 18) {
$errors[] = 'Age has to be 18+';
}
if (!empty($errors)) {
$e = new MyValidationException();
$e->myErrors = $errors;
throw $e;
}
} Then in custom error handler: $myErrorHandler = function(array $exceptions) {
$errors = [];
foreach ($exceptions as $exception) {
if ($exception->getPrevious() instanceof MyValidationException) {
foreach ($exception->getPrevious()->myErrors as $message) {
$errors[] = [/* Format the error as you want */];
}
} else {
$errors[] = [/* Format the error as you want */];
}
}
return $errors;
};
$result = GraphQL::executeQuery(/* $args */)
->setErrorsHandler($myErrorHandler)
->toArray(); |
Oh yeah, and one more option I keep forgetting about is to return an array of exceptions from your resolver (vs throwing them). But that's not certain. I remember that we discussed it at some point, just don't remember if it is actually implemented %) so try it yourself. |
Thank you! Very helpful answer. After some hacking with Overblog/GraphQLBundle I managed to successfully use my own error handler. The problem now is that I want to use the default handler in most cases (such as syntax errors in the GraphQL query) and only use the customized one for some of my own exception. Any tip how I can re-use the default handler? |
Ok I think I solved that on my own. Posting it here for anyone else looking for the same thing. $defaultFormatter = FormattedError::prepareFormatter(null, $debugMode);
$executionResult->setErrorFormatter(
function (\Throwable $exception) use ($defaultFormatter, $debugMode) {
if ($exception->getPrevious() instanceof MyException) {
return $this->formatException($exception->getPrevious(), $debugMode);
}
return $defaultFormatter($exception);
}
); |
Uh oh!
There was an error while loading. Please reload this page.
When resolving a mutation it can very easily result in multiple errors - especially validation of the user input. For example let's say I have a mutation like this:
The resolver for createPerson should add two errors to the result:
By throwing an exception implementing
GraphQL\Error\ClientAware
interface I can only add one error to the result. How can I add two (or more)?The text was updated successfully, but these errors were encountered: