Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-go): read an error message from any JSON body

Yudhi Armyndharisabea5fccc7f5
diff --git a/sdk/go/error_message_test.go b/sdk/go/error_message_test.go
new file mode 100644
index 000000000..18696f148
--- /dev/null
+++ b/sdk/go/error_message_test.go
@@ -0,0 +1,39 @@
+package openwa
+
+import (
+ "net/http"
+ "testing"
+)
+
+// The message comes from any JSON object body that carries one, not only from a body that decodes
+// as the whole Nest envelope, and an answer with no text names its status.
+func TestAPIErrorMessageFromAnyBody(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ body string
+ header http.Header
+ want string
+ kind string
+ }{
+ {"envelope", 400, `{"statusCode":400,"message":"bad thing","error":"Bad Request"}`, nil, "bad thing", "Bad Request"},
+ {"error is an object", 400, `{"statusCode":400,"message":"bad thing","error":{"x":1}}`, nil, "bad thing", ""},
+ {"status code is a string", 400, `{"statusCode":"400","message":"bad thing","error":"Bad Request"}`, nil, "bad thing", "Bad Request"},
+ {"no status code", 403, `{"message":"bad thing","error":"Forbidden"}`, nil, "bad thing", "Forbidden"},
+ {"array with a non-string", 400, `{"statusCode":400,"message":["a",{"b":1}]}`, nil, "a", ""},
+ {"array of strings", 400, `{"statusCode":400,"message":["a","b"],"error":"Bad Request"}`, nil, "a, b", "Bad Request"},
+ {"empty body", 502, ``, nil, "Bad Gateway", ""},
+ {"plain text", 502, `upstream down`, nil, "upstream down", ""},
+ {"redirect", 301, ``, http.Header{"Location": {"https://example.com/x"}}, "Unexpected redirect (not followed; the API key is never re-sent to a redirect target)", ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := parseAPIError(tc.status, []byte(tc.body), "GET /x", tc.header)
+ if got.Message != tc.want {
+ t.Errorf("message = %q, want %q", got.Message, tc.want)
+ }
+ if got.Kind != tc.kind {
+ t.Errorf("kind = %q, want %q", got.Kind, tc.kind)
+ }
+ })
+ }
+}
diff --git a/sdk/go/errors.go b/sdk/go/errors.go
index dfab85780..192f7ab1d 100644
--- a/sdk/go/errors.go
+++ b/sdk/go/errors.go
@@ -66,11 +66,12 @@ var (
type APIError struct {
// StatusCode is the HTTP status code of the response.
StatusCode int
- // Message is a human-readable description derived from the NestJS error
- // envelope (or the raw body when the response is not the standard shape).
+ // Message is a human-readable description: the "message" of the JSON body
+ // (the gateway's NestJS error envelope, or a proxy's own), the raw body when
+ // it is not JSON, else the text of the status.
Message string
- // Kind is the value of the NestJS envelope's "error" field (e.g.
- // "Not Found", "Conflict"), when present.
+ // Kind is the value of the body's "error" field (e.g. "Not Found",
+ // "Conflict"), when it is a string.
Kind string
// Body is the parsed JSON body, or the raw string when the body is not
// valid JSON.
@@ -135,45 +136,27 @@ func (e *TimeoutError) Error() string {
func (e *TimeoutError) Unwrap() error { return e.Err }
-// nestEnvelope is the standard NestJS error shape:
-// {"statusCode": int, "message": string|[]string, "error": string}.
-type nestEnvelope struct {
- StatusCode int `json:"statusCode"`
- Message json.RawMessage `json:"message"`
- Error string `json:"error"`
-}
-
-// parseAPIError builds an *APIError from a raw response body, extracting a
-// readable message from the NestJS envelope when the body matches that shape.
+// parseAPIError builds an *APIError from a raw response body. The message is read from any JSON
+// object that carries one, so an error from a proxy or WAF in front of the gateway reads like the
+// gateway's own.
func parseAPIError(status int, raw []byte, context string, header http.Header) *APIError {
var body any
- var envelope *nestEnvelope
-
if len(raw) > 0 {
if err := json.Unmarshal(raw, &body); err != nil {
body = string(raw)
}
- var env nestEnvelope
- if err := json.Unmarshal(raw, &env); err == nil && env.StatusCode != 0 {
- envelope = &env
- }
- }
-
- message := messageFromEnvelope(envelope, body)
- kind := ""
- if envelope != nil {
- kind = envelope.Error
}
+ fields, _ := body.(map[string]any)
+ kind, _ := fields["error"].(string)
apiErr := &APIError{
StatusCode: status,
- Message: message,
+ Message: messageFromBody(status, body),
Kind: kind,
Body: body,
Context: context,
Header: header,
}
- fields, _ := body.(map[string]any)
apiErr.Code, _ = fields["code"].(string)
// The body's retryAfterSeconds wins: send pacing puts its wait (possibly
// hours) only there, and a header added by a proxy must not shorten it.
@@ -185,20 +168,37 @@ func parseAPIError(status int, raw []byte, context string, header http.Header) *
return apiErr
}
-func messageFromEnvelope(envelope *nestEnvelope, body any) string {
- if envelope != nil && len(envelope.Message) > 0 {
- // message may be a string or an array of strings.
- var single string
- if err := json.Unmarshal(envelope.Message, &single); err == nil {
- return single
+// messageFromBody is the text of an error answer: the "message" of a JSON object (a string, or an
+// array whose strings are joined), else a plain-text body, else what the status itself says.
+func messageFromBody(status int, body any) string {
+ switch b := body.(type) {
+ case map[string]any:
+ switch m := b["message"].(type) {
+ case string:
+ if m != "" {
+ return m
+ }
+ case []any:
+ var parts []string
+ for _, p := range m {
+ if s, ok := p.(string); ok {
+ parts = append(parts, s)
+ }
+ }
+ if len(parts) > 0 {
+ return joinComma(parts)
+ }
}
- var many []string
- if err := json.Unmarshal(envelope.Message, &many); err == nil {
- return joinComma(many)
+ case string:
+ if b != "" {
+ return b
}
}
- if s, ok := body.(string); ok && s != "" {
- return s
+ if status >= 300 && status < 400 {
+ return "Unexpected redirect (not followed; the API key is never re-sent to a redirect target)"
+ }
+ if text := http.StatusText(status); text != "" {
+ return text
}
return "request failed"
}