Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relevant Http Response Code using graphql-js

Ok here's the thing, I'm trying to figure out how to deal with error handling with graphql-js. (In a case without Relay)

Not specific enough !? Ok so, since graphql-js is catching all errors thrown within resolve functions, I'm kind of confuse on how to deal properly with errors and http responses.

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

  1. Always return 200 OK with the graphql response even if containing errors. (Don't like that one)

  2. Switch case on the result.errors[0] and return an http response in respect of the error, returning result.data if no errors. (which could end up being a veeeery long switch case)

    • Deal with the error handling in the resolve function and throw and object (e.g. { httpCode: 404, msg: 'No X found with the requested id' } )

    • In the express app.post function(or whatever 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 doesn't currently work because of the way the error object is marshalled... or at least I haven't found how to get it out of graphql yet. I'm thinking of maybe looking into graphql-js source but I thought I better ask you guys first since I might be missing something obvious.

Obviously, a better idea is welcome !

Cheers :D

like image 395
Yormi Avatar asked Nov 10 '22 02:11

Yormi


1 Answers

I am also trying to figure this out.

The best I have managed to come up with is throwing a custom error in my resolver. Check out apollo-errors. I am not sure if this is the best way, but it could work for you.

like image 159
Ryan-Neal Mes Avatar answered Dec 23 '22 11:12

Ryan-Neal Mes