github.com/shippio/gqlgen@v0.0.0-20220912092219-633ea699ef07/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 errors they return
    27  func RegisterErrorType(code string, kind ErrorKind) {
    28  	codeType[code] = kind
    29  }
    30  
    31  // Set the error code on a given graphql error extension
    32  func Set(err error, value string) {
    33  	gqlErr, _ := err.(*gqlerror.Error)
    34  	if gqlErr.Extensions == nil {
    35  		gqlErr.Extensions = map[string]interface{}{}
    36  	}
    37  
    38  	gqlErr.Extensions["code"] = value
    39  }
    40  
    41  // get the kind of the first non User error, defaults to User if no errors have a custom extension
    42  func GetErrorKind(errs gqlerror.List) ErrorKind {
    43  	for _, err := range errs {
    44  		if code, ok := err.Extensions["code"].(string); ok {
    45  			if kind, ok := codeType[code]; ok && kind != KindUser {
    46  				return kind
    47  			}
    48  		}
    49  	}
    50  
    51  	return KindUser
    52  }