forked from graphql-go/graphql
/
formatted.go
62 lines (54 loc) · 1.34 KB
/
formatted.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package gqlerrors
import (
"errors"
"github.com/graphql-go/graphql/language/location"
)
type ExtendedError interface {
error
Extensions() map[string]interface{}
}
type FormattedError struct {
Message string `json:"message"`
Locations []location.SourceLocation `json:"locations"`
Path []interface{} `json:"path,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
}
func (g FormattedError) Error() string {
return g.Message
}
func NewFormattedError(message string) FormattedError {
err := errors.New(message)
return FormatError(err)
}
func FormatError(err error) FormattedError {
switch err := err.(type) {
case FormattedError:
return err
case *Error:
ret := FormattedError{
Message: err.Error(),
Locations: err.Locations,
Path: err.Path,
}
if err := err.OriginalError; err != nil {
if extended, ok := err.(ExtendedError); ok {
ret.Extensions = extended.Extensions()
}
}
return ret
case Error:
return FormatError(&err)
default:
return FormattedError{
Message: err.Error(),
Locations: []location.SourceLocation{},
}
}
}
func FormatErrors(errs ...error) []FormattedError {
formattedErrors := []FormattedError{}
for _, err := range errs {
formattedErrors = append(formattedErrors, FormatError(err))
}
return formattedErrors
}