diff --git a/errors/errors.go b/errors/errors.go index b373c95fb5f9a968459cc61f68cd345b78404eb6..0da300acf420d24ff7185ef35eb7ba5ac62d7f3a 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -1,6 +1,7 @@ package errors import ( + "errors" "fmt" "github.com/vektah/gqlparser/v2/gqlerror" @@ -28,6 +29,24 @@ // Sets the field name that caused the error func Field(err *gqlerror.Error, field string) *gqlerror.Error { err.Extensions["field"] = field return err +} + +// Returns true if the first GraphQL error has the same error code as the +// reference error. This should be used, for example, to test an error from +// client.Do against an error initialized by this module (e.g. +// ErrAccessDenied). These errors do not work with the Go standard library's +// errors.Is function, nor with ==, thus this function. +func Is(err error, ref *gqlerror.Error) bool { + var gqlerr *gqlerror.Error + if !errors.As(err, &gqlerr) { + return false + } + if code, ok := gqlerr.Extensions["code"]; ok { + if refCode, ok := ref.Extensions["code"]; ok { + return code == refCode + } + } + return false } // Error codes as string constants