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) *gqlerror.Error {
err.Extensions["field"] = field
return err
}
// Error codes as string constants
var (
AccessDenied ErrorCode = "ERR_ACCESS_DENIED"
NotFound ErrorCode = "ERR_NOT_FOUND"
Unsupported ErrorCode = "ERR_UNSUPPORTED"
Unauthorized ErrorCode = "ERR_UNAUTHORIZED"
InternalError ErrorCode = "ERR_INTERNAL"
Timeout ErrorCode = "ERR_TIMEOUT"
)
// Error codes as Go errors
var (
ErrAccessDenied = New(AccessDenied, "Access denied")
ErrNotFound = New(NotFound, "Resource not found")
ErrUnsupported = New(Unsupported, "Not supported")
ErrUnauthorized = New(Unauthorized, "Unauthorized")
ErrInternalError = New(InternalError, "Internal server error")
ErrTimeout = New(Timeout, "Operation timed out")
)