graphql-go/graphql

Add a `path` field to `FormattedError`?

sanae10001 opened this issue · 5 comments

nsf commented

In case if somebody decides to implement that, don't just add a path, but also it'd be nice to be able to do custom formatting on errors. Error should be an interface. For example see this article:

https://medium.com/@tarkus/validation-and-user-errors-in-graphql-mutations-39ca79cd00bf

GraphQL express middleware in js land has this hook "formatError", which allows you to return whatever you want as an error. The nice property of GraphQL errors themselves is that they can infer path info for you, but other than that it's very limited in a sense that there is only a message. Some people want custom error codes, etc. So it should be something like:

type CustomError interface {
   SetLocation(...)
   SetPath(...)
   ToJSON() []byte
   error
}

When a resolver returns an error, graphql lib should be able to set path/location for you, however what that error contains and how it produces JSON version of itself at the end is up to a lib user.

This is done in #363. And in regards to @nsf's comment, errors are now customizable to the extent that the spec allows: If your resolvers return an error that implements gqlerrors.ExtendedError, you can include arbitrary data in an "extensions" error field:

  "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"
      }
    }
  ]

Can anybody post an example? I try to add extensions to gqlerrors.ExtendedError in the resolver and return it as an error but the response message still don't show me the extension Field:

func (r resolver) LoginUser(params graphql.ResolveParams) (interface{}, error) {
    ...
    if err != nil {
        errf := gqlerrors.FormatError(err)
        errf.Extensions = map[string]interface{}{"code": "INVALID_ARGUMENT"}
        return nil, errf
    }
    return response, nil
}

GraphQl Response:

{
  "data": {
    "LoginUser": null
  },
  "errors": [
    {
      "message": "Invalid argument",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "LoginUser"
      ]
    }
  ]
}

@Raze92 Don’t return FormattedError from your resolvers. That struct is used to format errors returned by resolvers, and you probably will never need to use it directly. Just implement your own error type with an Extensions() method and return instances of it.

@Raze92 Don’t return FormattedError from your resolvers. That struct is used to format errors returned by resolvers, and you probably will never need to use it directly. Just implement your own error type with an Extensions() method and return instances of it.

That worked. Thanks!