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

Throwing error inside Subscription resolver #1539

Closed
DBL-Lee opened this issue Oct 2, 2018 · 2 comments
Closed

Throwing error inside Subscription resolver #1539

DBL-Lee opened this issue Oct 2, 2018 · 2 comments
Labels

Comments

@DBL-Lee
Copy link

DBL-Lee commented Oct 2, 2018

/label question

I would like to check for some permission before user subscribe to an endpoint. An error should be thrown and the client should be able to catch the error.

The following is what I am trying:

someSubscriptionEndpoint: {
	subscribe: (payload, args, context, info) => {
		throw new Error('Internal server error');
         }
}

But the error I receive on client side is "Subscription field must return Async Iterable. Received: [object Object]"

https://github.com/graphql/graphql-js/blob/master/src/subscription/subscribe.js#L272

This line is called twice, the first time eventStream is the error I threw so condition is true and the error is wrapped and rethrown. The second time I received { errors: [ [GraphQLError] ] } and the the error in line 281 is thrown.

What is the correct way of throwing an error when client subscribes to an specific subscription endpoint?

@danielrearden
Copy link
Contributor

danielrearden commented Jun 3, 2020

The subscribe method is not the resolver for the field. There is a separate resolve method you can specify that works exactly like the resolver for any other field.

someSubscriptionField: {
  subscribe: (payload, args, context, info) => {
    ...
  },
  resolve: (root, args, context, info) => {
    // add your validation logic here
    return root.someSubscriptionField
  }
}

Note that the root value will be whatever value was published. So you can publish any value and use the resolver to transform it. For example, instead of publishing an entire object, you could just publish the id and the resolve the field based on that.

@h-amg
Copy link

h-amg commented Jun 5, 2020

thanks @danielrearden

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