1

Previous When I made API server with RestAPI, I return data with HTTP status code.

So, Frontend receive status code from server, it determined request is success of fail.

I know that graphQL has error fields, and can refer it to solve this issue.

But I want to change response status code that send to client.

This way is correct and stable way?

Or, When use graphQL, do not change status code and just determine by error field is standard way?

Any suggestions would be appreciated :)

Thanks.

Hide
  • 3,199
  • 7
  • 41
  • 83

1 Answers1

3

[...] do not change status code and just determine by error field is standard way?

YES do not manage errors using status codes, they are Http related and GraphQL aim at being protocol/framework agnostic so that everything you need should be inside your output.

As you said there can be an errors field in your response:

The errors entry in the response is a non‐empty list of errors, where each error is a map.

If no errors were encountered during the requested operation, the errors entry should not be present in the result.

The spec states that errors field entries can have a field named extensions:

GraphQL services may provide an additional entry to errors with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to add additional information to errors however they see fit, and there are no additional restrictions on its contents.

Using the extensions field you can add custom machine-readable information to your errors like the key code here.

{
  "errors": [
    {
      "message": "Name for character with ID 1002 could not be fetched.",
      "locations": [ { "line": 6, "column": 7 } ],
      "path": [ "hero", "heroFriends", 1, "name" ],
      "extensions": {
        "code": "CAN_NOT_FETCH_BY_ID",
        "timestamp": "Fri Feb 9 14:33:09 UTC 2018"
      }
    }
  ]
}

Apollo Prophecy

To make error management easier I created a codegen CLI that generate throwable errors classes for the server and facilitate error handling for client.

https://github.com/theGlenn/apollo-prophecy

Community
  • 1
  • 1
Glenn Sonna
  • 1,853
  • 3
  • 19
  • 25