git.sr.ht/~sircmpwn/gqlgen@v0.0.0-20200522192042-c84d29a1c940/graphql/errcode/codes.go (about)

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