Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions errs/ERROR_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Typed errors render to **stderr** as one JSON object per process exit:
| `error.message` | informational | not safe to branch on |
| `error.hint` | informational | actionable recovery guidance |
| `error.log_id` | informational | upstream request id (server-side trace) |
| `error.upstream_error` | informational | complete Base structured error object (`data.error`, falling back to top-level `error`); retains upstream field names, nulls, false values and extensions; omitted when absent; does not override CLI taxonomy |
| `error.retryable` | wire-stable | `true` when present; omitted when `false` |
| `error.retry_after_seconds` | per-Subtype-stable | upstream-provided minimum delay before retry; emitted when available for retryable `api/rate_limit` and HTTP-backed `network` errors |
| `error.param` | per-Subtype-stable | single offending parameter (`ValidationError`); see **Validation parameters** |
Expand Down
4 changes: 4 additions & 0 deletions errs/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

package errs

import "encoding/json"

// Problem is the RFC 7807-aligned shared shape embedded by every typed error.
//
// Message is REQUIRED. Producers must populate it; an empty Message will make
Expand All @@ -29,6 +31,8 @@ type Problem struct {
LogID string `json:"log_id,omitempty"`
Troubleshooter string `json:"troubleshooter,omitempty"`
Retryable bool `json:"retryable,omitempty"`
// UpstreamError preserves the upstream structured error without changing CLI taxonomy.
UpstreamError json.RawMessage `json:"upstream_error,omitempty"`
}

// Error satisfies the standard `error` interface. A nil receiver is treated
Expand Down
23 changes: 21 additions & 2 deletions shortcuts/base/base_errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package base

import (
"encoding/json"
"errors"
"fmt"
"strings"
Expand Down Expand Up @@ -154,6 +155,20 @@ func baseAPIErrorFromResult(resultMap map[string]interface{}, cc errclass.Classi
if resultMap == nil {
return errs.NewInternalError(errs.SubtypeInvalidResponse, "API returned a malformed response envelope")
}
// Preserve the complete diagnostic before message/hint promotion consumes fields.
data, _ := resultMap["data"].(map[string]interface{})
detail, _ := data["error"].(map[string]interface{})
if detail == nil {
detail, _ = resultMap["error"].(map[string]interface{})
Comment thread
zgz2048 marked this conversation as resolved.
Resolved
}
var upstreamError json.RawMessage
if detail != nil {
encoded, marshalErr := json.Marshal(detail)
if marshalErr != nil {
return errs.NewInternalError(errs.SubtypeInvalidResponse, "API returned an invalid error detail").WithCause(marshalErr)
}
upstreamError = encoded
}
if msg := extractDataErrorMessage(resultMap); msg != "" {
resultMap["msg"] = msg
}
Expand All @@ -165,8 +180,11 @@ func baseAPIErrorFromResult(resultMap map[string]interface{}, cc errclass.Classi
if err == nil {
return nil
}
if p, ok := errs.ProblemOf(err); ok && hint != "" {
p.Hint = hint
if p, ok := errs.ProblemOf(err); ok {
p.UpstreamError = upstreamError
if hint != "" {
p.Hint = hint
}
}
return err
}
Expand All @@ -186,6 +204,7 @@ func enrichBaseAPIErrorFromBody(err error, body []byte, cc errclass.ClassifyCont
src, _ := errs.ProblemOf(enriched)
dst, _ := errs.ProblemOf(err)
if src != nil && dst != nil {
dst.UpstreamError = src.UpstreamError
dst.Message = src.Message
dst.Hint = src.Hint
// A body without log_id must not erase a header-derived LogID
Expand Down
46 changes: 46 additions & 0 deletions shortcuts/base/base_errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
package base

import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"

Expand Down Expand Up @@ -215,3 +218,46 @@ func assertProblemCode(t *testing.T, err error, code int, messageParts ...string
}
}
}

func TestBaseUpstreamErrorPreservesShapeAndCause(t *testing.T) {
for _, placement := range []string{"nested", "top-level"} {
t.Run(placement, func(t *testing.T) {
detail := json.RawMessage(`{"type":"not_found","message":"missing","hint":"list fields","retryable":false,"value":9007199254740993,"table":null,"extra":{"future":true}}`)
body := map[string]interface{}{"code": 800030201, "msg": "missing"}
if placement == "nested" {
body["data"] = map[string]interface{}{"error": detail}
} else {
body["error"] = detail
}
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
cause := assertErr{}
original := errs.NewAPIError(errs.SubtypeNotFound, "original").WithCode(800030201).WithCause(cause)
enriched := enrichBaseAPIErrorFromBody(original, raw, errclass.ClassifyContext{})
if enriched != original || !errors.Is(enriched, cause) {
t.Fatal("lost error identity/cause")
}
problem, _ := errs.ProblemOf(enriched)
// Compare decoded values using json.Number so large integers remain exact.
wantMap := map[string]interface{}{}
gotMap := map[string]interface{}{}
for _, item := range []struct {
raw []byte
target *map[string]interface{}
}{{detail, &wantMap}, {problem.UpstreamError, &gotMap}} {
decoder := json.NewDecoder(bytes.NewReader(item.raw))
decoder.UseNumber()
if err := decoder.Decode(item.target); err != nil {
t.Fatal(err)
}
}
want, _ := json.Marshal(wantMap)
got, _ := json.Marshal(gotMap)
if !bytes.Equal(want, got) {
t.Fatalf("detail=%s, want=%s", got, want)
}
})
}
}
47 changes: 47 additions & 0 deletions shortcuts/base/base_execute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4829,3 +4829,50 @@ func TestBaseViewExecutePropertyGettersAndExtendedSetters(t *testing.T) {
}
})
}

func TestBatchCreatePreservesUpstreamErrorOnWire(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
detail := map[string]interface{}{
"type": "not_found", "message": "not_found", "retryable": false,
"path": "create_records.0.MissingField", "value": "MissingField",
"table": map[string]interface{}{"id": "tbl_x", "name": "Orders"},
"hint": "List fields in the current table.", "docs_url": nil,
"extra_context": map[string]interface{}{"future": []interface{}{"detail", false}},
}
reg.Register(&httpmock.Stub{
Method: "POST", URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_create",
Body: map[string]interface{}{"code": 800030201, "msg": "not_found: not_found", "data": map[string]interface{}{"error": detail}},
})
err := runShortcut(t, BaseRecordBatchCreate, []string{"+record-batch-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"create_records":[{"MissingField":"value"}]}`}, factory, stdout)
if output.ExitCodeOf(err) != 1 {
t.Fatalf("exit=%d, err=%v", output.ExitCodeOf(err), err)
}
if stdout.Len() != 0 {
t.Fatalf("unexpected stdout: %s", stdout.String())
}
var stderr bytes.Buffer
if !output.WriteTypedErrorEnvelope(&stderr, err, "user") {
t.Fatal("expected typed error envelope")
}
var wire struct {
OK bool `json:"ok"`
Error struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
Code int `json:"code"`
Hint string `json:"hint"`
UpstreamError map[string]interface{} `json:"upstream_error"`
} `json:"error"`
}
if err := json.Unmarshal(stderr.Bytes(), &wire); err != nil {
t.Fatal(err)
}
if wire.OK || wire.Error.Type != "api" || wire.Error.Subtype != "unknown" || wire.Error.Code != 800030201 || wire.Error.Hint != detail["hint"] {
t.Fatalf("unexpected wire: %s", stderr.String())
}
want, _ := json.Marshal(detail)
got, _ := json.Marshal(wire.Error.UpstreamError)
if !bytes.Equal(want, got) {
t.Fatalf("upstream error=%s, want=%s", got, want)
}
}
Loading