graphql / graphql-spec

GraphQL is a query language and execution engine tied to any backend service.
https://spec.graphql.org
14.28k stars 1.12k forks source link

Add `why` field to GraphQL Errors #893

Open IvanGoncharov opened 2 years ago

IvanGoncharov commented 2 years ago

TL;DR:

This RFC proposes adding the why field to GraphQL errors that contain a list of reasons why this error happened.

Problem Statement

Sometimes, during execution multiple errors happening at the same time (e.g. parallel execution) or to provide full context on what happens you need to chain errors.

Recent changes in JS, added two features AggregatedError and Error.cause to solve both problems but we don't have any mechanism to represent this additional error context in graphql.

But I don't think this proposal is JS specific and other languages have also mechanisms for aggregated errors and chains of errors.

TBD: Examples in other languages

🧑‍💻 Proposed Solution

Add ability to attach an array of sub-errors to graphql error under a property named why (the name is up to discussion). With following limitations:

  1. why is an optional non-empty array of objects
  2. Each individual object should contain only message property (required) and extensions(optional)

🎬 Behavior

Error chaining:

{
  "errors": [
    {
      "message": "Expected value of type "DateTime", found "07/11/2021"",
      "locations": [ { "line": 6, "column": 7 } ],
      "why": [{
        message: "Invalid date-time please specify in 'yyyy-MM-dd'T'HH:mm:ss.SSSZ' format"
      }],
    }
  ]
}

Aggregated errors:


{
  "errors": [
    {
      "message": "Failed to fetch all necessary data",
      "why": [
        {
          message: "Failed to fetch from https://example.com/api/resource/1"
        },
        {
          message: "Failed to fetch from https://example.com/api/resource/2"
        },
      ],
    }
  ]
}
leebyron commented 2 years ago

Note, there is a very similar ECMAScript proposal here https://github.com/tc39/proposal-error-cause

leebyron commented 2 years ago

Bikeshed, could merge the two related proposals with a key name like "causes"

IvanGoncharov commented 2 years ago

Moving to Stage1 per Oct2021 WG discussion.