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