~bigbes/core-go

522372683c08fc166e1a0da0e05cbf18d4e2fa7f — Drew DeVault 8 months ago e272a4c
errors: add errors.Is
1 files changed, 19 insertions(+), 0 deletions(-)

M errors/errors.go
M errors/errors.go => errors/errors.go +19 -0
@@ 1,6 1,7 @@
package errors

import (
	"errors"
	"fmt"

	"github.com/vektah/gqlparser/v2/gqlerror"


@@ 30,6 31,24 @@ func Field(err *gqlerror.Error, field string) *gqlerror.Error {
	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
var (
	AccessDenied  ErrorCode = "ERR_ACCESS_DENIED"