Search code examples
node.jsgraphqlapollo-server

How to avoid wrapping errors collection in a error object in Apollo Server V2 in error response


We are migrating our Apollo Graphql Server v1 projects to v2.

We noticed that there is a change in the error response format.

In v2, the errors list in the response is wrapped within an error object.

But, in v1, it is not so. We want to have a a consistent standard and not introduce the wrapping behaviour in v2.

I understand that GraphQL services may provide add additional fields via extensions as per below link. Link: https://graphql.github.io/graphql-spec/June2018/#sec-Errors

I have tested Apollo GraphQL V2 and this is how it is implemented there.

In v1 it is as expected.

In v1,we see error response as below,


{
  "errors": [
    {
      "message": "Field \"announcement\" must not have a selection since type \"String\" has no subfields.",
      "locations": [
        {
          "line": 2,
          "column": 16
        }
      ]
    }
  ]
}

In v2, we see error response as below,

{
  "error": {
    "errors": [
      {
        "message": "Field \"announcement\" must not have a selection since type \"String\" has no subfields.",
        "locations": [
          {
            "line": 2,
            "column": 16
          }
        ],
        "extensions": {
          "code": "GRAPHQL_VALIDATION_FAILED",
          "exception": {
            "stacktrace": [
             ...
            ]
          }
        }
      }
    ]
  }
}

In v1 error response, errors list is not wrapped inside error object. In v2,it is wrapped in error object.

But, my question is why is the errors list wrapped inside a error object in v2. In v1, there was only the errors list in the response.

We follow a standard for all services (both REST and non-REST) to have a standard format and it was as per the v1 version. But, now we see it has been wrapped in a error object.

Is there any way we can configure Apollo Server to not wrap the errors list within a error object.


Solution

  • This behavior has not changed in version 2. Apollo Server produces spec-compliant responses and does not not wrap any resulting errors in an error object. Instead, this is just a known bug with GraphQL Playground. With version 2.0, Apollo Server transition from GraphiQL to GraphQL Playground. GraphiQL did not have this same issue, which is why this looks like a bug with Apollo Server. Check the network tab and look at the actual response from your server -- it's actually in the expected format.