~bigbes/core-go

8e729e7539f47f682d74d11071ef5c86f89f0505 — Drew DeVault 1 year, 5 months ago dbdf194
errors: new module for common GQL errors

This package provides a means of creating GraphQL-aware errors and
a location for common error codes.
1 files changed, 42 insertions(+), 0 deletions(-)

A errors/errors.go
A errors/errors.go => errors/errors.go +42 -0
@@ 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")
)