github.com/newrelic/newrelic-client-go@v1.1.0/pkg/alerts/nerdgraph.go (about)

     1  package alerts
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/newrelic/newrelic-client-go/internal/http"
     8  )
     9  
    10  // NerdGraphQueryWithContext works similarly to the default client's NerdGraphQueryWithContext but with a custom error
    11  // value that provides enhanced error messages and context via GraphQLErrorResponse.
    12  func (a *Alerts) NerdGraphQueryWithContext(ctx context.Context, query string, vars map[string]interface{}, respBody interface{}) error {
    13  	req, err := a.client.NewNerdGraphRequest(query, vars, respBody)
    14  	if err != nil {
    15  		return err
    16  	}
    17  
    18  	req.WithContext(ctx)
    19  	req.SetErrorValue(&GraphQLErrorResponse{})
    20  
    21  	_, err = a.client.Do(req)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	return nil
    27  }
    28  
    29  // GraphQLErrorResponse is a special GraphQL response produced by Alerts GraphQL Service and provides additional context
    30  type GraphQLErrorResponse struct {
    31  	http.GraphQLErrorResponse
    32  
    33  	Errors []struct {
    34  		Message    string   `json:"message"`
    35  		Path       []string `json:"path"`
    36  		Extensions struct {
    37  			Code             string `json:"code"`
    38  			ErrorClass       string `json:"errorClass"`
    39  			ErrorCode        string `json:"error_code,omitempty"`
    40  			ValidationErrors []struct {
    41  				Name   string `json:"name"`
    42  				Reason string `json:"reason"`
    43  			} `json:"validationErrors"`
    44  		} `json:"extensions"`
    45  	} `json:"errors"`
    46  }
    47  
    48  func (r *GraphQLErrorResponse) Error() string {
    49  	if len(r.Errors) > 0 {
    50  		var messages []string
    51  
    52  		for _, e := range r.Errors {
    53  			if e.Message != "" {
    54  				messages = append(messages, e.Message)
    55  			}
    56  		}
    57  		return strings.Join(messages, ", ")
    58  	}
    59  
    60  	return ""
    61  }
    62  
    63  func (r *GraphQLErrorResponse) IsNotFound() bool {
    64  	for _, err := range r.Errors {
    65  		if strings.Contains(err.Message, "Not Found") {
    66  			return true
    67  		}
    68  	}
    69  
    70  	return false
    71  }
    72  
    73  func (r *GraphQLErrorResponse) New() http.ErrorResponse {
    74  	return &GraphQLErrorResponse{}
    75  }