From 8a60321f6ffe42c42cfec6a2d253742ef13a8acf Mon Sep 17 00:00:00 2001 From: Jacob Bednarz Date: Mon, 17 Oct 2022 13:11:20 +1100 Subject: [PATCH] cloudflare: update `RequestError` to expose `Messages` The messages field isn't really used broadly in the API as it was designed for informational feedback as opposed to errors, however, the page rules endpoint uses it to communicate validation failures. For these messages to be raised in other tools, namely the Terraform provider, it needs a dedicated field on the struct and to be included in the `Error()` method. Closes cloudflare/terraform-provider-cloudflare#1579 --- .changelog/1106.txt | 3 +++ cloudflare.go | 4 ++-- errors.go | 23 ++++++++++++++++++++++- 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 .changelog/1106.txt diff --git a/.changelog/1106.txt b/.changelog/1106.txt new file mode 100644 index 000000000..da158169d --- /dev/null +++ b/.changelog/1106.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +cloudflare: expose `Messages` from the `Response` object +``` diff --git a/cloudflare.go b/cloudflare.go index 68576c025..9219f7239 100644 --- a/cloudflare.go +++ b/cloudflare.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "io/ioutil" @@ -16,8 +17,6 @@ import ( "strings" "time" - "errors" - "golang.org/x/time/rate" ) @@ -347,6 +346,7 @@ func (api *API) makeRequestWithAuthTypeAndHeadersComplete(ctx context.Context, m Errors: errBody.Errors, ErrorCodes: errCodes, ErrorMessages: errMsgs, + Messages: errBody.Messages, } switch resp.StatusCode { diff --git a/errors.go b/errors.go index 14e045474..9b92d1dca 100644 --- a/errors.go +++ b/errors.go @@ -70,6 +70,9 @@ type Error struct { // ErrorMessages is a list of all the error codes. ErrorMessages []string + // Messages is a list of informational messages provided by the endpoint. + Messages []ResponseInfo + // RayID is the internal identifier for the request that was made. RayID string } @@ -90,7 +93,21 @@ func (e Error) Error() string { errMessages = append(errMessages, m) } - return errString + strings.Join(errMessages, ", ") + msgs := []string{} + for _, m := range e.Messages { + msgs = append(msgs, m.Message) + } + + errString += strings.Join(errMessages, ", ") + + // `Messages` is primarily used for additional validation failure notes in + // page rules. This shouldn't be used going forward but instead, use the + // error fields appropriately. + if len(msgs) > 0 { + errString += "\n" + strings.Join(msgs, " \n") + } + + return errString } // RequestError is for 4xx errors that we encounter not covered elsewhere @@ -119,6 +136,10 @@ func (e RequestError) InternalErrorCodeIs(code int) bool { return e.cloudflareError.InternalErrorCodeIs(code) } +func (e RequestError) Messages() []ResponseInfo { + return e.cloudflareError.Messages +} + func (e RequestError) RayID() string { return e.cloudflareError.RayID }