github.com/99designs/gqlgen@v0.17.45/graphql/errcode/codes.go (about) 1 package errcode 2 3 import ( 4 "github.com/vektah/gqlparser/v2/gqlerror" 5 ) 6 7 const ( 8 ValidationFailed = "GRAPHQL_VALIDATION_FAILED" 9 ParseFailed = "GRAPHQL_PARSE_FAILED" 10 ) 11 12 type ErrorKind int 13 14 const ( 15 // issues with graphql (validation, parsing). 422s in http, GQL_ERROR in websocket 16 KindProtocol ErrorKind = iota 17 // user errors, 200s in http, GQL_DATA in websocket 18 KindUser 19 ) 20 21 var codeType = map[string]ErrorKind{ 22 ValidationFailed: KindProtocol, 23 ParseFailed: KindProtocol, 24 } 25 26 // RegisterErrorType should be called by extensions that want to customize the http status codes for 27 // errors they return 28 func RegisterErrorType(code string, kind ErrorKind) { 29 codeType[code] = kind 30 } 31 32 // Set the error code on a given graphql error extension 33 func Set(err error, value string) { 34 if err == nil { 35 return 36 } 37 gqlErr, ok := err.(*gqlerror.Error) 38 if !ok { 39 return 40 } 41 42 if gqlErr.Extensions == nil { 43 gqlErr.Extensions = map[string]interface{}{} 44 } 45 46 gqlErr.Extensions["code"] = value 47 } 48 49 // get the kind of the first non User error, defaults to User if no errors have a custom extension 50 func GetErrorKind(errs gqlerror.List) ErrorKind { 51 for _, err := range errs { 52 if code, ok := err.Extensions["code"].(string); ok { 53 if kind, ok := codeType[code]; ok && kind != KindUser { 54 return kind 55 } 56 } 57 } 58 59 return KindUser 60 }