From 3954a9ef535187e20872e4afc0a425ed64a21a70 Mon Sep 17 00:00:00 2001 From: Terin Stock Date: Thu, 18 Jan 2024 00:01:00 +0100 Subject: [PATCH] feat(cfapi): include Ray ID in signing errors To allow for customer support and engineering teams to correlate failures to API requests from failure reports, include the request's Ray ID in error messages --- internal/cfapi/cfapi.go | 9 +++++++-- internal/cfapi/cfapi_test.go | 4 +++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/internal/cfapi/cfapi.go b/internal/cfapi/cfapi.go index bfcab0f..0fd8e2a 100644 --- a/internal/cfapi/cfapi.go +++ b/internal/cfapi/cfapi.go @@ -82,10 +82,11 @@ type APIResponse struct { type APIError struct { Code int `json:"code"` Message string `json:"message"` + RayID string `json:"-"` } func (a *APIError) Error() string { - return fmt.Sprintf("Cloudflare API Error code=%d message=%s", a.Code, a.Message) + return fmt.Sprintf("Cloudflare API Error code=%d message=%s ray_id=%s", a.Code, a.Message, a.RayID) } func (c *Client) Sign(ctx context.Context, req *SignRequest) (*SignResponse, error) { @@ -108,13 +109,17 @@ func (c *Client) Sign(ctx context.Context, req *SignRequest) (*SignResponse, err } defer resp.Body.Close() + rayID := resp.Header.Get("CF-Ray") + api := APIResponse{} if err := json.NewDecoder(resp.Body).Decode(&api); err != nil { return nil, err } if !api.Success { - return nil, &api.Errors[0] + err := &api.Errors[0] + err.RayID = rayID + return nil, err } signResp := SignResponse{} diff --git a/internal/cfapi/cfapi_test.go b/internal/cfapi/cfapi_test.go index ff3e85c..6d2ac03 100644 --- a/internal/cfapi/cfapi_test.go +++ b/internal/cfapi/cfapi_test.go @@ -80,6 +80,7 @@ func TestSign(t *testing.T) { }{ {name: "API success", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("cf-ray", "0123456789abcdef-ABC") fmt.Fprintln(w, `{ "success": true, "errors": [], @@ -109,6 +110,7 @@ func TestSign(t *testing.T) { { name: "API error", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("cf-ray", "0123456789abcdef-ABC") fmt.Fprintln(w, `{ "success": false, "errors": [{"code": 9001, "message": "Over Nine Thousand!"}], @@ -117,7 +119,7 @@ func TestSign(t *testing.T) { }`) }), response: nil, - error: "Cloudflare API Error code=9001 message=Over Nine Thousand!", + error: "Cloudflare API Error code=9001 message=Over Nine Thousand! ray_id=0123456789abcdef-ABC", }, }