formatted.go

 1package gqlerrors
 2
 3import (
 4	"errors"
 5
 6	"github.com/graphql-go/graphql/language/location"
 7)
 8
 9type FormattedError struct {
10	Message   string                    `json:"message"`
11	Locations []location.SourceLocation `json:"locations"`
12}
13
14func (g FormattedError) Error() string {
15	return g.Message
16}
17
18func NewFormattedError(message string) FormattedError {
19	err := errors.New(message)
20	return FormatError(err)
21}
22
23func FormatError(err error) FormattedError {
24	switch err := err.(type) {
25	case FormattedError:
26		return err
27	case *Error:
28		return FormattedError{
29			Message:   err.Error(),
30			Locations: err.Locations,
31		}
32	case Error:
33		return FormattedError{
34			Message:   err.Error(),
35			Locations: err.Locations,
36		}
37	default:
38		return FormattedError{
39			Message:   err.Error(),
40			Locations: []location.SourceLocation{},
41		}
42	}
43}
44
45func FormatErrors(errs ...error) []FormattedError {
46	formattedErrors := []FormattedError{}
47	for _, err := range errs {
48		formattedErrors = append(formattedErrors, FormatError(err))
49	}
50	return formattedErrors
51}