error.go

 1package gqlerrors
 2
 3import (
 4	"fmt"
 5	"reflect"
 6
 7	"github.com/graphql-go/graphql/language/ast"
 8	"github.com/graphql-go/graphql/language/location"
 9	"github.com/graphql-go/graphql/language/source"
10)
11
12type Error struct {
13	Message       string
14	Stack         string
15	Nodes         []ast.Node
16	Source        *source.Source
17	Positions     []int
18	Locations     []location.SourceLocation
19	OriginalError error
20}
21
22// implements Golang's built-in `error` interface
23func (g Error) Error() string {
24	return fmt.Sprintf("%v", g.Message)
25}
26
27func NewError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int, origError error) *Error {
28	if stack == "" && message != "" {
29		stack = message
30	}
31	if source == nil {
32		for _, node := range nodes {
33			// get source from first node
34			if node == nil || reflect.ValueOf(node).IsNil() {
35				continue
36			}
37			if node.GetLoc() != nil {
38				source = node.GetLoc().Source
39			}
40			break
41		}
42	}
43	if len(positions) == 0 && len(nodes) > 0 {
44		for _, node := range nodes {
45			if node == nil || reflect.ValueOf(node).IsNil() {
46				continue
47			}
48			if node.GetLoc() == nil {
49				continue
50			}
51			positions = append(positions, node.GetLoc().Start)
52		}
53	}
54	locations := []location.SourceLocation{}
55	for _, pos := range positions {
56		loc := location.GetLocation(source, pos)
57		locations = append(locations, loc)
58	}
59	return &Error{
60		Message:       message,
61		Stack:         stack,
62		Nodes:         nodes,
63		Source:        source,
64		Positions:     positions,
65		Locations:     locations,
66		OriginalError: origError,
67	}
68}