Skip to content
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

Why are error results thrown? #704

Closed
inceddy opened this issue Jul 13, 2020 · 3 comments
Closed

Why are error results thrown? #704

inceddy opened this issue Jul 13, 2020 · 3 comments
Labels

Comments

@inceddy
Copy link

inceddy commented Jul 13, 2020

In my current application I have a fixed number of common exceptions that might occure while resolving a mutation.
To handle this scenario I have created a UnionType combining the expected ObjectResultType and several ErrorResultTypes.
I thought I could catch the exceptions in a try-catch block within the resolver and then pass them down to resolveType, but unexpectedly Throwable results are thrown again .

Why is this behaviour important?

@spawnia
Copy link
Collaborator

spawnia commented Jul 13, 2020

That behaviour seems like it might be a leftover from porting the graphql-js reference implementation. There, resolving fields is usually done async inside of a Promise. There is some weirdness when throwing in async functions, so this might mechanism might be there to smooth things over.

I tried to disable the re-throwing and found that it causes 21 tests to fail.

@inceddy
Copy link
Author

inceddy commented Jul 14, 2020

Ok seems to be something deeply nested within graphql-php. I'll find another solution, but stumbling across this behavior made me curious.

@vladar
Copy link
Member

vladar commented Jul 20, 2020

Yeah, you can return exceptions from resolvers, not just throw them.

Why is this behaviour important?

There are several use-cases where this is useful. One is when you use lists:

"resolve" => function () {
    return [
        "item1",
        new MyException("Error with item2"),
        "item3",
    ];
}

The other is when some parent resolver decides that a field must be an error:

"resolve" => function () {
    return [
        'title' => 'My Title',
        'secureContent' => new MyException("You can't read this"),
    ];
}

If this exception occurs in a nullable field - this field is replaced with null, otherwise the first ancestor nullable field is replaced with null (and errors are added to result). See also #374 (comment)

I guess you could just wrap your custom exceptions to work around this OR use a non-throwable class for such errors.

Another potential solution is to utilize the context: #432 (comment)

Closing this as answered but feel free to follow-up if you have questions.

@vladar vladar closed this as completed Jul 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants