Corresponding Http response code using graphql-js

Ok, here's what I'm trying to figure out how to handle error handling with graphql-js. (In case of no relay)

Not quite clear! So, since graphql-js catches all errors that occur inside the resolution functions, I'm a little confused about how to handle HTTP errors and responses correctly.

I had few ideas and would like to know what you think about it!

  • Always return 200 OK with graphql response, even if they contain errors. (Don't like this one)

  • Replace the register with result.errors [0] and return an HTTP response regarding the error, returning result.data if there are no errors. (which could be the time when it was a long switch)

    • Handle the error handling in the resolution function as well as drop the object (for example, { httpCode: 404, msg: 'No X found with the requested id' } )

    • In the app.post express application (or any other web framework), having something like:

       app.post('/graphql', function(req, res) { let result = await graphql(req.body); if(result.errors.size) { let e = result.errors[0]; res.status(e.httpCode).send(e.msg); } res.json(result.data); } 

    This currently does not work due to how the error object is sorted ... or at least I have not yet found how to get it from the graph. I think that I might be looking at the source of graphql-js, but I thought it was better to ask you guys since I could have missed something obvious.

Obviously, an idea is better welcomed!

Greetings: D

+5
source share
1 answer

I am also trying to figure this out.

The best I managed to come up with was throwing a custom error into my resolver. Check apollo-errors . I'm not sure if this is the best way, but it might work for you.

+1
source

Source: https://habr.com/ru/post/1234449/


All Articles