From 8e729e7539f47f682d74d11071ef5c86f89f0505 Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Thu, 6 Mar 2025 10:59:10 +0100 Subject: [PATCH] errors: new module for common GQL errors This package provides a means of creating GraphQL-aware errors and a location for common error codes. --- errors/errors.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 errors/errors.go diff --git a/errors/errors.go b/errors/errors.go new file mode 100644 index 0000000000000000000000000000000000000000..89bda63b273c29787d5803f405ecac1558df851f --- /dev/null +++ b/errors/errors.go @@ -0,0 +1,42 @@ +package errors + +import ( + "fmt" + + "github.com/vektah/gqlparser/v2/gqlerror" +) + +type ErrorCode string + +// Creates a new GraphQL error with a standard error code. +func New(code ErrorCode, message string) *gqlerror.Error { + return &gqlerror.Error{ + Message: message, + Extensions: map[string]any{"code": code}, + } +} + +// Creates a new GraphQL error with a standard error code. +func Errorf(code ErrorCode, format string, a ...any) *gqlerror.Error { + return &gqlerror.Error{ + Message: fmt.Sprintf(format, a...), + Extensions: map[string]any{"code": code}, + } +} + +// Sets the field name that caused the error +func Field(err *gqlerror.Error, field string) { + err.Extensions["field"] = field +} + +// Error codes as string constants +var ( + AccessDenied ErrorCode = "ERR_ACCESS_DENIED" + NotFound ErrorCode = "ERR_NOT_FOUND" +) + +// Error codes as Go errors +var ( + ErrAccessDenied = New(AccessDenied, "Access denied") + ErrNotFound = New(NotFound, "Resource not found") +)