cubefs
78 строк · 2.0 Кб
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 {
13Message string
14Stack string
15Nodes []ast.Node
16Source *source.Source
17Positions []int
18Locations []location.SourceLocation
19OriginalError error
20Path []interface{}
21}
22
23// implements Golang's built-in `error` interface
24func (g Error) Error() string {
25return fmt.Sprintf("%v", g.Message)
26}
27
28func NewError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int, origError error) *Error {
29return newError(message, nodes, stack, source, positions, nil, origError)
30}
31
32func NewErrorWithPath(message string, nodes []ast.Node, stack string, source *source.Source, positions []int, path []interface{}, origError error) *Error {
33return newError(message, nodes, stack, source, positions, path, origError)
34}
35
36func newError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int, path []interface{}, origError error) *Error {
37if stack == "" && message != "" {
38stack = message
39}
40if source == nil {
41for _, node := range nodes {
42// get source from first node
43if node == nil || reflect.ValueOf(node).IsNil() {
44continue
45}
46if node.GetLoc() != nil {
47source = node.GetLoc().Source
48}
49break
50}
51}
52if len(positions) == 0 && len(nodes) > 0 {
53for _, node := range nodes {
54if node == nil || reflect.ValueOf(node).IsNil() {
55continue
56}
57if node.GetLoc() == nil {
58continue
59}
60positions = append(positions, node.GetLoc().Start)
61}
62}
63locations := []location.SourceLocation{}
64for _, pos := range positions {
65loc := location.GetLocation(source, pos)
66locations = append(locations, loc)
67}
68return &Error{
69Message: message,
70Stack: stack,
71Nodes: nodes,
72Source: source,
73Positions: positions,
74Locations: locations,
75OriginalError: origError,
76Path: path,
77}
78}
79