Mixing of schema-level and app-level errors in GraphQL

守給你的承諾、 提交于 2019-12-04 06:35:16
Ahmad Ferdous

The problem with error categorization

top-level graphql errors, and the application errors in the mutation payload

The distinction that you made between schema-level and application level errors is based on GraphQL type and mutation implementation. A client-side application usually expects a higher abstraction level of errors, i.e., it needs to distinguish user errors and system errors. That way it can mask the system errors as "internal error" and present the user errors as necessary. The developer also can inspect the set of system errors.

See a nice and concise article by Konstantin Tarkus on this: Validation and User Errors in GraphQL Mutations, whose approach I have followed in this answer.

A Not-so-standard-yet-makes-sense solution

To the best of my knowledge, there is no particular standard approach. However, you can try out the following approach.

First, having system-level errors in the top-level field errors of mutation response:

{
  "data": {
    "viewer": {
      "articles": {
        "edges": [
          {
            "node": {
              "title": "Sample article title",
              "tags": null
            }
          }
        ]
      }
    }
  },
  "errors": [
    {
      "message": "Cannot read property 'bar' of undefined",
      "locations": [
        {
          "line": 7,
          "column": 11
        }
      ]
    }
  ]
}

Second, putting user-level errors as a separate field errors in mutation payload. Example from the mentioned article:

{
  data: {
    user: null,
    errors: [
      '',
      'Failed to create a new user account.',
      'email',
      'User with this email address was already registered.',
    ]
  }
}
// The errors field is just an array of strings that follows this pattern —
// [argumentName1, errorMessage1, argumentName2, errorMessage2, … ]

The above approach enables the client to look for user errors in a defined format in a single place - the errors field of mutation payload. It also allows the client to receive all errors together.

This approach loses automatic validation of the mutation's input type. However, validation is not compromised as the input type's validation logic can be put in a separate function. This function will return validation errors as necessary, which will eventually be put in mutation payload's errors field.

By the way, thanks for the well-written question!

If you are using Apollo, you can easily multiplex the errors array in the graphql response for both graphql errors AND custom errors that are machine readable using this package:

https://github.com/thebigredgeek/apollo-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!