gqlerror

package
v2.5.64 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 9 Imported by: 1,041

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CollectAttrs added in v2.5.62

func CollectAttrs(err error) []slog.Attr

CollectAttrs reports the attributes of every error in err's tree, merged so that no key appears twice at any level. It is what logging middleware should pass to slog for a GraphQL error.

It visits err and then what Unwrap returns, depth first and, for Unwrap() []error, left to right, taking Attrs() []slog.Attr from each error that has the method. Groups with the same key are merged, so a cause reporting a "gql" group of its own adds keys to this package's group rather than repeating it, which JSON readers would resolve by dropping one of the two. For any other key reported twice, the first value found wins: the outermost error's, which is normally the *Error the GraphQL response carried.

Attributes follow slog's rules: values are resolved, a group with an empty key is inlined, and a zero Attr or an empty group is dropped. Keys keep the order they first appear in. The result is nil when nothing is reported. No error's attributes are modified.

A cause reporting into the "gql" group should not reuse the keys Error.Attrs reports for its own meaning: message, path, locations, extensions and rule.

Like errors.Is, CollectAttrs does not guard against an Unwrap cycle.

Example
package main

import (
	"context"
	"log/slog"
	"os"

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

// nullError stands in for a cause that reports into the "gql" group, as gqlgen's
// InvalidNullError does.
type nullError struct{ field string }

func (e *nullError) Error() string { return e.field + " is null" }

func (e *nullError) Attrs() []slog.Attr {
	return []slog.Attr{slog.Group("gql", slog.String("field", e.field))}
}

func main() {
	err := gqlerror.WrapPath(ast.Path{ast.PathName("b")}, &nullError{field: "Errors.b"})

	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if len(groups) == 0 && (a.Key == slog.TimeKey || a.Key == slog.LevelKey) {
				return slog.Attr{} // keep the output stable and short
			}
			return a
		},
	}))
	logger.LogAttrs(context.Background(), slog.LevelError, "graphql error",
		gqlerror.CollectAttrs(err)...)

}
Output:
{"msg":"graphql error","gql":{"message":"Errors.b is null","path":"b","field":"Errors.b"}}

Types

type Error

type Error struct {
	Err        error          `json:"-"`
	Message    string         `json:"message"`
	Path       ast.Path       `json:"path,omitempty"`
	Locations  []Location     `json:"locations,omitempty"`
	Extensions map[string]any `json:"extensions,omitempty"`
	Rule       string         `json:"-"`
}

Error is the standard graphql error type described in https://spec.graphql.org/draft/#sec-Errors

func ErrorLocf

func ErrorLocf(file string, line, col int, message string, args ...any) *Error

func ErrorPathf

func ErrorPathf(path ast.Path, message string, args ...any) *Error

func ErrorPosf

func ErrorPosf(pos *ast.Position, message string, args ...any) *Error

func Errorf

func Errorf(message string, args ...any) *Error

func Wrap added in v2.5.2

func Wrap(err error) *Error

func WrapIfUnwrapped added in v2.5.9

func WrapIfUnwrapped(err error) *Error

func WrapPath

func WrapPath(path ast.Path, err error) *Error

func WrapPos added in v2.5.59

func WrapPos(pos *ast.Position, err error) *Error

func (*Error) AsError added in v2.5.9

func (err *Error) AsError() error

func (*Error) Attrs added in v2.5.61

func (err *Error) Attrs() []slog.Attr

Attrs reports the error's own fields as a single slog group named "gql": message, path, locations, extensions and rule, each left out when empty. The result is nil when every field is empty, or for a nil *Error.

The group keeps these keys from colliding with a cause's: gqlgen's InvalidNullError, for one, reports a path of its own.

Err is not reported. Attrs means an error's own attributes, never its cause's, so a walk that collects Attrs from every error in a chain visits the cause exactly once. CollectAttrs is that walk, and it merges a cause's "gql" group into this one.

func (*Error) Error

func (err *Error) Error() string

func (*Error) SetFile

func (err *Error) SetFile(file string)

func (*Error) Unwrap added in v2.1.0

func (err *Error) Unwrap() error

Unwrap returns the cause, or nil for a nil *Error. Wrap, WrapPath and WrapPos return a nil *Error for a nil cause, and once that is stored in an error it is not == nil, so errors.Is and errors.As would otherwise dereference it.

type ErrorWithSources added in v2.5.37

type ErrorWithSources struct {
	Err        error            `json:"-"`
	Message    string           `json:"message"`
	Path       ast.Path         `json:"path,omitempty"`
	Locations  []SourceLocation `json:"locations,omitempty"`
	Extensions map[string]any   `json:"extensions,omitempty"`
	Rule       string           `json:"-"`
	// contains filtered or unexported fields
}

ErrorWithSources is the source-aware validation error returned by the opt-in validator API. It retains the standard GraphQL error fields while Locations stores each location together with its source document. Source is omitted from JSON, leaving the standard GraphQL line and column fields.

func NewErrorWithSources added in v2.5.37

func NewErrorWithSources(err *Error, locations []SourceLocation) *ErrorWithSources

NewErrorWithSources pairs an existing GraphQL error with source-aware locations. The location slice is copied so callers cannot change the error's source associations by mutating their input slice.

A non-empty locations must describe err's own locations: one per location, in the same order and at the same coordinates. It panics otherwise, including when err has no locations at all, because sources can annotate locations but not invent them. An empty locations pairs err's locations with no sources.

func (*ErrorWithSources) AsError added in v2.5.37

func (err *ErrorWithSources) AsError() error

func (*ErrorWithSources) Attrs added in v2.5.61

func (err *ErrorWithSources) Attrs() []slog.Attr

Attrs reports the error's own fields as Error.Attrs does, in the same "gql" group under the same keys. Each location also names its source document, when it has one: in JSON as a "source" field beside "line" and "column", and in text as name:line:column.

The *ast.Source itself is not logged. It would print as a pointer, and it holds the whole document.

func (*ErrorWithSources) Error added in v2.5.37

func (err *ErrorWithSources) Error() string

func (*ErrorWithSources) SourceLocations added in v2.5.37

func (err *ErrorWithSources) SourceLocations() []SourceLocation

SourceLocations returns a shallow copy of the source-aware locations in validation order.

func (*ErrorWithSources) UnmarshalJSON added in v2.5.37

func (err *ErrorWithSources) UnmarshalJSON(data []byte) error

UnmarshalJSON discards source documents because GraphQL error JSON does not encode them.

func (*ErrorWithSources) Unwrap added in v2.5.37

func (err *ErrorWithSources) Unwrap() error

type List

type List []*Error

func (List) As added in v2.2.0

func (errs List) As(target any) bool

func (List) Error

func (errs List) Error() string

func (List) Is added in v2.2.0

func (errs List) Is(target error) bool

func (List) Unwrap added in v2.5.11

func (errs List) Unwrap() []error

type Location

type Location struct {
	Line   int `json:"line,omitempty"`
	Column int `json:"column,omitempty"`
}

func (Location) String added in v2.5.61

func (l Location) String() string

String writes the location as line:column, the form Error's message uses after the file name.

type SourceList added in v2.5.37

type SourceList []*ErrorWithSources

SourceList is the result type returned by the opt-in source-aware validator APIs.

func (SourceList) As added in v2.5.37

func (errs SourceList) As(target any) bool

func (SourceList) Error added in v2.5.37

func (errs SourceList) Error() string

func (SourceList) Is added in v2.5.37

func (errs SourceList) Is(target error) bool

func (SourceList) Unwrap added in v2.5.37

func (errs SourceList) Unwrap() []error

type SourceLocation added in v2.5.37

type SourceLocation struct {
	Line   int         `json:"line,omitempty"`
	Column int         `json:"column,omitempty"`
	Source *ast.Source `json:"-"`
}

SourceLocation pairs a GraphQL line and column with its source document. Source is nil when the location has no source document.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL