From 761a9c0a084b4f548d71a24d613026af0a2ea589 Mon Sep 17 00:00:00 2001 From: zgz2048 Date: Thu, 29 Oct 2026 16:27:04 +0800 Subject: [PATCH 1/5] fix(base): preserve complete upstream error details --- errs/ERROR_CONTRACT.md | 1 + errs/problem.go | 4 +++ internal/errclass/codemeta_base.go | 3 +- shortcuts/base/base_errors.go | 23 ++++++++++++-- shortcuts/base/base_errors_test.go | 46 ++++++++++++++++++++++++++++ shortcuts/base/base_execute_test.go | 47 +++++++++++++++++++++++++++++ 6 files changed, 121 insertions(+), 3 deletions(-) diff --git a/errs/ERROR_CONTRACT.md b/errs/ERROR_CONTRACT.md index b91e11f68f..426f90dd48 100644 --- a/errs/ERROR_CONTRACT.md +++ b/errs/ERROR_CONTRACT.md @@ -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** | diff --git a/errs/problem.go b/errs/problem.go index 0208c8733c..7096f95dd4 100644 --- a/errs/problem.go +++ b/errs/problem.go @@ -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 @@ -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 diff --git a/internal/errclass/codemeta_base.go b/internal/errclass/codemeta_base.go index b2651fabb8..c7db779fb2 100644 --- a/internal/errclass/codemeta_base.go +++ b/internal/errclass/codemeta_base.go @@ -7,7 +7,8 @@ import "github.com/larksuite/cli/errs" var baseCodeMeta = map[int]CodeMeta{ // Base write-path errors. - 1254291: {Category: errs.CategoryAPI, Subtype: errs.SubtypeConflict, Retryable: true}, + 800030201: {Category: errs.CategoryAPI, Subtype: errs.SubtypeNotFound}, + 1254291: {Category: errs.CategoryAPI, Subtype: errs.SubtypeConflict, Retryable: true}, // Copy Table domain errors (technical design chapter 18.2). 800020304: {Category: errs.CategoryAuthorization, Subtype: errs.SubtypePermissionDenied}, diff --git a/shortcuts/base/base_errors.go b/shortcuts/base/base_errors.go index a352ca7bf8..0d4f529e52 100644 --- a/shortcuts/base/base_errors.go +++ b/shortcuts/base/base_errors.go @@ -4,6 +4,7 @@ package base import ( + "encoding/json" "errors" "fmt" "strings" @@ -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{}) + } + 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 } @@ -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 } @@ -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 diff --git a/shortcuts/base/base_errors_test.go b/shortcuts/base/base_errors_test.go index 61d4083713..26e7c19d4e 100644 --- a/shortcuts/base/base_errors_test.go +++ b/shortcuts/base/base_errors_test.go @@ -4,6 +4,9 @@ package base import ( + "bytes" + "encoding/json" + "errors" "strings" "testing" @@ -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) + } + }) + } +} diff --git a/shortcuts/base/base_execute_test.go b/shortcuts/base/base_execute_test.go index b49f2e5bd4..c390838de3 100644 --- a/shortcuts/base/base_execute_test.go +++ b/shortcuts/base/base_execute_test.go @@ -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 != "not_found" || 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) + } +} From c447550e7ba7f76140bde86bc838d23e6927cefa Mon Sep 17 00:00:00 2001 From: zgz2048 Date: Fri, 30 Oct 2026 15:18:50 +0800 Subject: [PATCH 2/5] fix(base): leave existing error code mappings unchanged --- internal/errclass/codemeta_base.go | 3 +-- shortcuts/base/base_execute_test.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/internal/errclass/codemeta_base.go b/internal/errclass/codemeta_base.go index c7db779fb2..b2651fabb8 100644 --- a/internal/errclass/codemeta_base.go +++ b/internal/errclass/codemeta_base.go @@ -7,8 +7,7 @@ import "github.com/larksuite/cli/errs" var baseCodeMeta = map[int]CodeMeta{ // Base write-path errors. - 800030201: {Category: errs.CategoryAPI, Subtype: errs.SubtypeNotFound}, - 1254291: {Category: errs.CategoryAPI, Subtype: errs.SubtypeConflict, Retryable: true}, + 1254291: {Category: errs.CategoryAPI, Subtype: errs.SubtypeConflict, Retryable: true}, // Copy Table domain errors (technical design chapter 18.2). 800020304: {Category: errs.CategoryAuthorization, Subtype: errs.SubtypePermissionDenied}, diff --git a/shortcuts/base/base_execute_test.go b/shortcuts/base/base_execute_test.go index c390838de3..b189acfe2c 100644 --- a/shortcuts/base/base_execute_test.go +++ b/shortcuts/base/base_execute_test.go @@ -4867,7 +4867,7 @@ func TestBatchCreatePreservesUpstreamErrorOnWire(t *testing.T) { if err := json.Unmarshal(stderr.Bytes(), &wire); err != nil { t.Fatal(err) } - if wire.OK || wire.Error.Type != "api" || wire.Error.Subtype != "not_found" || wire.Error.Code != 800030201 || wire.Error.Hint != detail["hint"] { + 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) From 16fe98cdfb8267dffbd212988a986b2b5302d1f6 Mon Sep 17 00:00:00 2001 From: zgz2048 Date: Thu, 5 Nov 2026 15:23:51 +0800 Subject: [PATCH 3/5] fix(base): preserve error details without changing Problem --- cmd/root.go | 1 + cmd/root_test.go | 34 +++++++++++++++++++++++ errs/ERROR_CONTRACT.md | 2 +- errs/problem.go | 4 --- internal/output/errors.go | 44 ++++++++++++++++++++++++++---- shortcuts/base/base_errors.go | 19 ++++++------- shortcuts/base/base_errors_test.go | 34 ++++++++++++++++++++--- 7 files changed, 113 insertions(+), 25 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 270606412b..1a1261e316 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -305,6 +305,7 @@ func handleRootError( // reusable error value. if !errs.IsRaw(err) { renderedErr = presentRootError(f, err, projector) + renderedErr = output.WithUpstreamError(renderedErr, output.UpstreamErrorOf(err)) } // Staged dispatch: capture the typed exit code BEFORE attempting the diff --git a/cmd/root_test.go b/cmd/root_test.go index ec76926053..fbd0cd3de6 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -480,6 +480,40 @@ func TestHandleRootError_PartialWritePreservesExitCode(t *testing.T) { } } +func TestHandleRootError_PreservesUpstreamDetailAfterPresentation(t *testing.T) { + t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) + f, stdout, stderr, _ := cmdutil.TestFactory(t, nil) + typed := &errs.SecurityPolicyError{ + Problem: errs.Problem{ + Category: errs.CategoryPolicy, + Subtype: errs.SubtypeChallengeRequired, + Code: 21000, + Message: "blocked by access policy", + }, + ChallengeURL: "https://example.com/challenge", + } + err := output.WithUpstreamError(typed, json.RawMessage(`false`)) + if exit := handleRootError(f, err, nil); exit != int(output.ExitContentSafety) { + t.Fatalf("exit = %d, want %d", exit, output.ExitContentSafety) + } + if stdout.Len() != 0 { + t.Fatalf("unexpected stdout: %s", stdout) + } + var env struct { + Error struct { + Code int `json:"code"` + ChallengeURL string `json:"challenge_url"` + UpstreamError json.RawMessage `json:"upstream_error"` + } `json:"error"` + } + if err := json.Unmarshal(stderr.Bytes(), &env); err != nil { + t.Fatalf("decode stderr: %v\n%s", err, stderr) + } + if env.Error.Code != typed.Code || env.Error.ChallengeURL != typed.ChallengeURL || string(env.Error.UpstreamError) != "false" { + t.Fatalf("unexpected stderr: %s", stderr) + } +} + // TestHandleRootError_BareErrorExitCodeNoStderr pins the silent-exit // contract: a *output.BareError is honored for its exit code while stderr stays // empty (stdout already carries the result, so the dispatcher must not layer a diff --git a/errs/ERROR_CONTRACT.md b/errs/ERROR_CONTRACT.md index 426f90dd48..54c1bf2d18 100644 --- a/errs/ERROR_CONTRACT.md +++ b/errs/ERROR_CONTRACT.md @@ -61,7 +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.upstream_error` | informational | complete Base error detail from `data.error` when the key exists, including explicit `null` or `false`; falls back to top-level `error` only when `data.error` is absent; omitted when neither key exists; 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** | diff --git a/errs/problem.go b/errs/problem.go index 7096f95dd4..0208c8733c 100644 --- a/errs/problem.go +++ b/errs/problem.go @@ -3,8 +3,6 @@ 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 @@ -31,8 +29,6 @@ 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 diff --git a/internal/output/errors.go b/internal/output/errors.go index 051f3f3894..cc37682c8c 100644 --- a/internal/output/errors.go +++ b/internal/output/errors.go @@ -39,6 +39,30 @@ func PartialFailure(code int) *PartialFailureError { return &PartialFailureError{Code: code} } +type upstreamError struct { + error + detail json.RawMessage +} + +func (e *upstreamError) Unwrap() error { return e.error } + +// WithUpstreamError attaches an optional upstream detail for stderr rendering. +func WithUpstreamError(err error, detail json.RawMessage) error { + if err == nil || len(detail) == 0 { + return err + } + return &upstreamError{error: err, detail: detail} +} + +// UpstreamErrorOf returns the detail attached to an error chain, if present. +func UpstreamErrorOf(err error) json.RawMessage { + var carrier *upstreamError + if errors.As(err, &carrier) { + return carrier.detail + } + return nil +} + // WriteTypedErrorEnvelope writes the JSON error envelope for a typed error. // Each typed error owns its wire shape via its own struct tags: Problem fields // are promoted to the top level through embedding, and extension fields @@ -75,6 +99,18 @@ func WriteTypedErrorEnvelope(w io.Writer, err error, identity string) bool { enc := json.NewEncoder(&buf) enc.SetEscapeHTML(false) enc.SetIndent("", " ") + if detail := UpstreamErrorOf(err); len(detail) != 0 { + if err := enc.Encode(env.Error); err != nil { + return false + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(buf.Bytes(), &fields); err != nil || fields == nil { + return false + } + buf.Reset() + fields["upstream_error"] = detail + env.Error = fields + } if encErr := enc.Encode(env); encErr != nil { // Encoding failed — emit nothing here; the dispatcher's fall-through // branches still surface the error, so stderr is never blank. @@ -108,13 +144,11 @@ func withEffectiveRequestURL(err error) error { return rendered } -// typedEnvelope wraps a typed error for wire emission. Error is `error` so the -// underlying typed error's own json tags determine the inner shape via -// encoding/json reflection; Notice mirrors the success Envelope's notice (see -// GetNotice in envelope.go). +// typedEnvelope uses the concrete typed error's JSON shape, with optional +// upstream detail added alongside its fields. Notice mirrors the success envelope. type typedEnvelope struct { OK bool `json:"ok"` Identity string `json:"identity,omitempty"` - Error error `json:"error"` + Error any `json:"error"` Notice map[string]interface{} `json:"_notice,omitempty"` } diff --git a/shortcuts/base/base_errors.go b/shortcuts/base/base_errors.go index 0d4f529e52..50f08ee251 100644 --- a/shortcuts/base/base_errors.go +++ b/shortcuts/base/base_errors.go @@ -157,12 +157,12 @@ func baseAPIErrorFromResult(resultMap map[string]interface{}, cc errclass.Classi } // 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{}) + detail, exists := data["error"] + if !exists { + detail, exists = resultMap["error"] } var upstreamError json.RawMessage - if detail != nil { + if exists { encoded, marshalErr := json.Marshal(detail) if marshalErr != nil { return errs.NewInternalError(errs.SubtypeInvalidResponse, "API returned an invalid error detail").WithCause(marshalErr) @@ -180,13 +180,10 @@ func baseAPIErrorFromResult(resultMap map[string]interface{}, cc errclass.Classi if err == nil { return nil } - if p, ok := errs.ProblemOf(err); ok { - p.UpstreamError = upstreamError - if hint != "" { - p.Hint = hint - } + if p, ok := errs.ProblemOf(err); ok && hint != "" { + p.Hint = hint } - return err + return output.WithUpstreamError(err, upstreamError) } func enrichBaseAPIErrorFromBody(err error, body []byte, cc errclass.ClassifyContext) error { @@ -204,7 +201,6 @@ 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 @@ -212,6 +208,7 @@ func enrichBaseAPIErrorFromBody(err error, body []byte, cc errclass.ClassifyCont if src.LogID != "" { dst.LogID = src.LogID } + return output.WithUpstreamError(err, output.UpstreamErrorOf(enriched)) } return err } diff --git a/shortcuts/base/base_errors_test.go b/shortcuts/base/base_errors_test.go index 26e7c19d4e..454c9af1f6 100644 --- a/shortcuts/base/base_errors_test.go +++ b/shortcuts/base/base_errors_test.go @@ -12,6 +12,7 @@ import ( "github.com/larksuite/cli/errs" "github.com/larksuite/cli/internal/errclass" + "github.com/larksuite/cli/internal/output" ) func TestErrorDetailHelpers(t *testing.T) { @@ -236,17 +237,17 @@ func TestBaseUpstreamErrorPreservesShapeAndCause(t *testing.T) { 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") + var typed *errs.APIError + if !errors.As(enriched, &typed) || typed != original || !errors.Is(enriched, cause) { + t.Fatal("lost typed 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}} { + }{{detail, &wantMap}, {output.UpstreamErrorOf(enriched), &gotMap}} { decoder := json.NewDecoder(bytes.NewReader(item.raw)) decoder.UseNumber() if err := decoder.Decode(item.target); err != nil { @@ -261,3 +262,28 @@ func TestBaseUpstreamErrorPreservesShapeAndCause(t *testing.T) { }) } } + +func TestBaseUpstreamErrorPrefersPresentDataError(t *testing.T) { + for _, tc := range []struct { + name string + body string + want string + }{ + {"nested object", `{"code":800030201,"data":{"error":{"path":"nested"}},"error":{"path":"top"}}`, `{"path":"nested"}`}, + {"explicit null", `{"code":800030201,"data":{"error":null},"error":{"path":"top"}}`, `null`}, + {"explicit false", `{"code":800030201,"data":{"error":false},"error":{"path":"top"}}`, `false`}, + {"fallback", `{"code":800030201,"data":{},"error":{"path":"top"}}`, `{"path":"top"}`}, + {"absent", `{"code":800030201,"data":{}}`, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + original := errs.NewAPIError(errs.SubtypeNotFound, "original").WithCode(800030201) + err := enrichBaseAPIErrorFromBody(original, []byte(tc.body), errclass.ClassifyContext{}) + if _, ok := errs.ProblemOf(err); !ok { + t.Fatalf("expected typed error, got %v", err) + } + if got := string(output.UpstreamErrorOf(err)); got != tc.want { + t.Fatalf("upstream error=%q, want %q", got, tc.want) + } + }) + } +} From fdd45eb686235d9dbc4020cdac04bc2661753a3e Mon Sep 17 00:00:00 2001 From: zgz2048 Date: Thu, 5 Nov 2026 15:49:22 +0800 Subject: [PATCH 4/5] fix(base): include upstream diagnostics in error hints --- cmd/root.go | 1 - cmd/root_test.go | 34 -------- errs/ERROR_CONTRACT.md | 1 - internal/output/errors.go | 44 ++-------- shortcuts/base/base_errors.go | 119 +++++++++++++++------------- shortcuts/base/base_errors_test.go | 109 ++++++------------------- shortcuts/base/base_execute_test.go | 60 +++++++------- shortcuts/base/base_role_common.go | 5 +- shortcuts/base/helpers.go | 7 +- 9 files changed, 126 insertions(+), 254 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 1a1261e316..270606412b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -305,7 +305,6 @@ func handleRootError( // reusable error value. if !errs.IsRaw(err) { renderedErr = presentRootError(f, err, projector) - renderedErr = output.WithUpstreamError(renderedErr, output.UpstreamErrorOf(err)) } // Staged dispatch: capture the typed exit code BEFORE attempting the diff --git a/cmd/root_test.go b/cmd/root_test.go index fbd0cd3de6..ec76926053 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -480,40 +480,6 @@ func TestHandleRootError_PartialWritePreservesExitCode(t *testing.T) { } } -func TestHandleRootError_PreservesUpstreamDetailAfterPresentation(t *testing.T) { - t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) - f, stdout, stderr, _ := cmdutil.TestFactory(t, nil) - typed := &errs.SecurityPolicyError{ - Problem: errs.Problem{ - Category: errs.CategoryPolicy, - Subtype: errs.SubtypeChallengeRequired, - Code: 21000, - Message: "blocked by access policy", - }, - ChallengeURL: "https://example.com/challenge", - } - err := output.WithUpstreamError(typed, json.RawMessage(`false`)) - if exit := handleRootError(f, err, nil); exit != int(output.ExitContentSafety) { - t.Fatalf("exit = %d, want %d", exit, output.ExitContentSafety) - } - if stdout.Len() != 0 { - t.Fatalf("unexpected stdout: %s", stdout) - } - var env struct { - Error struct { - Code int `json:"code"` - ChallengeURL string `json:"challenge_url"` - UpstreamError json.RawMessage `json:"upstream_error"` - } `json:"error"` - } - if err := json.Unmarshal(stderr.Bytes(), &env); err != nil { - t.Fatalf("decode stderr: %v\n%s", err, stderr) - } - if env.Error.Code != typed.Code || env.Error.ChallengeURL != typed.ChallengeURL || string(env.Error.UpstreamError) != "false" { - t.Fatalf("unexpected stderr: %s", stderr) - } -} - // TestHandleRootError_BareErrorExitCodeNoStderr pins the silent-exit // contract: a *output.BareError is honored for its exit code while stderr stays // empty (stdout already carries the result, so the dispatcher must not layer a diff --git a/errs/ERROR_CONTRACT.md b/errs/ERROR_CONTRACT.md index 54c1bf2d18..b91e11f68f 100644 --- a/errs/ERROR_CONTRACT.md +++ b/errs/ERROR_CONTRACT.md @@ -61,7 +61,6 @@ 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 error detail from `data.error` when the key exists, including explicit `null` or `false`; falls back to top-level `error` only when `data.error` is absent; omitted when neither key exists; 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** | diff --git a/internal/output/errors.go b/internal/output/errors.go index cc37682c8c..051f3f3894 100644 --- a/internal/output/errors.go +++ b/internal/output/errors.go @@ -39,30 +39,6 @@ func PartialFailure(code int) *PartialFailureError { return &PartialFailureError{Code: code} } -type upstreamError struct { - error - detail json.RawMessage -} - -func (e *upstreamError) Unwrap() error { return e.error } - -// WithUpstreamError attaches an optional upstream detail for stderr rendering. -func WithUpstreamError(err error, detail json.RawMessage) error { - if err == nil || len(detail) == 0 { - return err - } - return &upstreamError{error: err, detail: detail} -} - -// UpstreamErrorOf returns the detail attached to an error chain, if present. -func UpstreamErrorOf(err error) json.RawMessage { - var carrier *upstreamError - if errors.As(err, &carrier) { - return carrier.detail - } - return nil -} - // WriteTypedErrorEnvelope writes the JSON error envelope for a typed error. // Each typed error owns its wire shape via its own struct tags: Problem fields // are promoted to the top level through embedding, and extension fields @@ -99,18 +75,6 @@ func WriteTypedErrorEnvelope(w io.Writer, err error, identity string) bool { enc := json.NewEncoder(&buf) enc.SetEscapeHTML(false) enc.SetIndent("", " ") - if detail := UpstreamErrorOf(err); len(detail) != 0 { - if err := enc.Encode(env.Error); err != nil { - return false - } - var fields map[string]json.RawMessage - if err := json.Unmarshal(buf.Bytes(), &fields); err != nil || fields == nil { - return false - } - buf.Reset() - fields["upstream_error"] = detail - env.Error = fields - } if encErr := enc.Encode(env); encErr != nil { // Encoding failed — emit nothing here; the dispatcher's fall-through // branches still surface the error, so stderr is never blank. @@ -144,11 +108,13 @@ func withEffectiveRequestURL(err error) error { return rendered } -// typedEnvelope uses the concrete typed error's JSON shape, with optional -// upstream detail added alongside its fields. Notice mirrors the success envelope. +// typedEnvelope wraps a typed error for wire emission. Error is `error` so the +// underlying typed error's own json tags determine the inner shape via +// encoding/json reflection; Notice mirrors the success Envelope's notice (see +// GetNotice in envelope.go). type typedEnvelope struct { OK bool `json:"ok"` Identity string `json:"identity,omitempty"` - Error any `json:"error"` + Error error `json:"error"` Notice map[string]interface{} `json:"_notice,omitempty"` } diff --git a/shortcuts/base/base_errors.go b/shortcuts/base/base_errors.go index 50f08ee251..83226fbc2d 100644 --- a/shortcuts/base/base_errors.go +++ b/shortcuts/base/base_errors.go @@ -7,13 +7,17 @@ import ( "encoding/json" "errors" "fmt" + "maps" "strings" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" + "github.com/larksuite/cli/errs" "github.com/larksuite/cli/extension/fileio" "github.com/larksuite/cli/internal/errclass" "github.com/larksuite/cli/internal/output" "github.com/larksuite/cli/internal/util" + "github.com/larksuite/cli/shortcuts/common" ) func handleBaseAPIResult(result interface{}, err error, action string) (map[string]interface{}, error) { @@ -151,39 +155,76 @@ func baseUploadAttachmentError(filePath string, err error) error { return errs.NewInternalError(errs.SubtypeSDKError, "failed to upload attachment %s: %s", filePath, err).WithCause(err) } +// classifyBaseAPIResponse applies the CLI's HTTP classification and then adds +// Base diagnostics from the response body to the resulting typed error. +func classifyBaseAPIResponse(runtime *common.RuntimeContext, resp *larkcore.ApiResp) error { + if _, err := runtime.ClassifyAPIResponse(resp); err != nil { + if statusErr := baseHTTPStatusErrorFromInvalidResponse(resp, err); statusErr != nil { + return statusErr + } + return enrichBaseAPIErrorFromBody(err, resp.RawBody, runtime.APIClassifyContext()) + } + return nil +} + +// baseAPIErrorFromResult promotes the selected Base error detail into the +// standard CLI message and hint while classifying by the response's code. func baseAPIErrorFromResult(resultMap map[string]interface{}, cc errclass.ClassifyContext) error { 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, exists := data["error"] - if !exists { - detail, exists = resultMap["error"] - } - var upstreamError json.RawMessage - if exists { - encoded, marshalErr := json.Marshal(detail) - if marshalErr != nil { - return errs.NewInternalError(errs.SubtypeInvalidResponse, "API returned an invalid error detail").WithCause(marshalErr) + rawDetail, nested := data["error"] + if !nested { + rawDetail = resultMap["error"] + } + detail, _ := rawDetail.(map[string]interface{}) + classified := maps.Clone(resultMap) + if nested { + if message, _ := detail["message"].(string); strings.TrimSpace(message) != "" { + classified["msg"] = strings.TrimSpace(message) + } + // The common classifier otherwise prefers error.message over msg. + if topLevel, ok := resultMap["error"].(map[string]interface{}); ok { + topLevel = maps.Clone(topLevel) + delete(topLevel, "message") + classified["error"] = topLevel } - upstreamError = encoded - } - if msg := extractDataErrorMessage(resultMap); msg != "" { - resultMap["msg"] = msg } - hint := extractErrorHint(resultMap) if logID := extractBaseErrorLogID(resultMap); logID != "" { - resultMap["log_id"] = logID + classified["log_id"] = logID } - err := errclass.BuildAPIError(resultMap, cc) - if err == nil { - return nil + err := errclass.BuildAPIError(classified, cc) + if p, ok := errs.ProblemOf(err); ok { + if hint, _ := detail["hint"].(string); strings.TrimSpace(hint) != "" { + p.Hint = strings.TrimSpace(hint) + } + p.Hint = appendBaseDebugInfo(p.Hint, detail) + } + return err +} + +// appendBaseDebugInfo appends the Base context as JSON values so strings and +// composite input values remain distinguishable inside the hint. +func appendBaseDebugInfo(hint string, detail map[string]interface{}) string { + var fields []string + for _, key := range []string{"path", "value", "table"} { + value, exists := detail[key] + if !exists { + continue + } + if encoded, err := json.Marshal(value); err == nil { + fields = append(fields, key+"="+string(encoded)) + } } - if p, ok := errs.ProblemOf(err); ok && hint != "" { - p.Hint = hint + if len(fields) == 0 { + return hint } - return output.WithUpstreamError(err, upstreamError) + debug := "debug_info: " + strings.Join(fields, ";") + if hint == "" { + return debug + } + return hint + "\n" + debug } func enrichBaseAPIErrorFromBody(err error, body []byte, cc errclass.ClassifyContext) error { @@ -208,7 +249,6 @@ func enrichBaseAPIErrorFromBody(err error, body []byte, cc errclass.ClassifyCont if src.LogID != "" { dst.LogID = src.LogID } - return output.WithUpstreamError(err, output.UpstreamErrorOf(enriched)) } return err } @@ -237,39 +277,6 @@ func extractBaseErrorLogID(resultMap map[string]interface{}) string { return "" } -func extractErrorHint(resultMap map[string]interface{}) string { - if detail, ok := resultMap["error"].(map[string]interface{}); ok { - if hint := consumeStringField(detail, "hint"); hint != "" { - return hint - } - } - data, _ := resultMap["data"].(map[string]interface{}) - if detail, ok := data["error"].(map[string]interface{}); ok { - if hint := consumeStringField(detail, "hint"); hint != "" { - return hint - } - } - return "" -} - -func extractDataErrorMessage(resultMap map[string]interface{}) string { - data, _ := resultMap["data"].(map[string]interface{}) - if detail, ok := data["error"].(map[string]interface{}); ok { - if message := consumeStringField(detail, "message"); message != "" { - return message - } - } - return "" -} - -func consumeStringField(src map[string]interface{}, key string) string { - value, _ := src[key].(string) - if _, exists := src[key]; exists { - delete(src, key) - } - return strings.TrimSpace(value) -} - func baseContentSafetyBlockError(scanResult output.ScanResult) error { message := "content safety violation detected" var rules []string diff --git a/shortcuts/base/base_errors_test.go b/shortcuts/base/base_errors_test.go index 454c9af1f6..452cf6bc54 100644 --- a/shortcuts/base/base_errors_test.go +++ b/shortcuts/base/base_errors_test.go @@ -4,30 +4,13 @@ package base import ( - "bytes" - "encoding/json" - "errors" "strings" "testing" "github.com/larksuite/cli/errs" "github.com/larksuite/cli/internal/errclass" - "github.com/larksuite/cli/internal/output" ) -func TestErrorDetailHelpers(t *testing.T) { - detail := map[string]interface{}{"message": "boom", "hint": "retry later"} - if got := extractErrorHint(map[string]interface{}{"data": map[string]interface{}{"error": detail}}); got != "retry later" { - t.Fatalf("hint=%q", got) - } - if got := extractDataErrorMessage(map[string]interface{}{"data": map[string]interface{}{"error": detail}}); got != "boom" { - t.Fatalf("message=%q", got) - } - if got := extractDataErrorMessage(map[string]interface{}{"data": map[string]interface{}{}}); got != "" { - t.Fatalf("message=%q", got) - } -} - func TestHandleBaseAPIResultErrorPaths(t *testing.T) { if _, err := handleBaseAPIResultAny(nil, assertErr{}, "list fields"); err == nil || !strings.Contains(err.Error(), "list fields") { t.Fatalf("err=%v", err) @@ -89,7 +72,7 @@ func TestHandleBaseAPIResultPromotesBaseErrorFields(t *testing.T) { if p.Message != "The cell value does not match the expected input shape." { t.Fatalf("message=%q", p.Message) } - if p.Hint != "Provide a number value." { + if want := "Provide a number value.\n" + `debug_info: path="Amount";value="abc";table={"id":"tbl_1","name":"Orders"}`; p.Hint != want { t.Fatalf("hint=%q", p.Hint) } if p.LogID != "20260508160000000000000000000000" { @@ -97,6 +80,28 @@ func TestHandleBaseAPIResultPromotesBaseErrorFields(t *testing.T) { } } +func TestBaseAPIErrorDetailPriority(t *testing.T) { + for _, tc := range []struct { + name string + body string + message string + hint string + }{ + {"nested", `{"code":800030201,"data":{"error":{"message":"nested","value":null}},"error":{"message":"top","path":"ignored"}}`, "nested", `debug_info: value=null`}, + {"fallback", `{"code":800030201,"data":{},"error":{"message":"top","path":"field"}}`, "top", `debug_info: path="field"`}, + {"explicit null", `{"code":800030201,"msg":"summary","data":{"error":null},"error":{"message":"top","path":"ignored"}}`, "summary", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + original := errs.NewAPIError(errs.SubtypeUnknown, "outer failure").WithCode(800030201) + err := enrichBaseAPIErrorFromBody(original, []byte(tc.body), errclass.ClassifyContext{}) + p, ok := errs.ProblemOf(err) + if !ok || err != original || p.Message != tc.message || p.Hint != tc.hint { + t.Fatalf("problem=%+v, want message=%q and hint=%q", p, tc.message, tc.hint) + } + }) + } +} + func TestHandleBaseAPIResultClassifiesKnownPermissionCode(t *testing.T) { result := map[string]interface{}{ "code": 99991676, @@ -219,71 +224,3 @@ 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{}) - var typed *errs.APIError - if !errors.As(enriched, &typed) || typed != original || !errors.Is(enriched, cause) { - t.Fatal("lost typed error identity/cause") - } - // 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}, {output.UpstreamErrorOf(enriched), &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) - } - }) - } -} - -func TestBaseUpstreamErrorPrefersPresentDataError(t *testing.T) { - for _, tc := range []struct { - name string - body string - want string - }{ - {"nested object", `{"code":800030201,"data":{"error":{"path":"nested"}},"error":{"path":"top"}}`, `{"path":"nested"}`}, - {"explicit null", `{"code":800030201,"data":{"error":null},"error":{"path":"top"}}`, `null`}, - {"explicit false", `{"code":800030201,"data":{"error":false},"error":{"path":"top"}}`, `false`}, - {"fallback", `{"code":800030201,"data":{},"error":{"path":"top"}}`, `{"path":"top"}`}, - {"absent", `{"code":800030201,"data":{}}`, ""}, - } { - t.Run(tc.name, func(t *testing.T) { - original := errs.NewAPIError(errs.SubtypeNotFound, "original").WithCode(800030201) - err := enrichBaseAPIErrorFromBody(original, []byte(tc.body), errclass.ClassifyContext{}) - if _, ok := errs.ProblemOf(err); !ok { - t.Fatalf("expected typed error, got %v", err) - } - if got := string(output.UpstreamErrorOf(err)); got != tc.want { - t.Fatalf("upstream error=%q, want %q", got, tc.want) - } - }) - } -} diff --git a/shortcuts/base/base_execute_test.go b/shortcuts/base/base_execute_test.go index b189acfe2c..6cea01873c 100644 --- a/shortcuts/base/base_execute_test.go +++ b/shortcuts/base/base_execute_test.go @@ -4830,49 +4830,51 @@ func TestBaseViewExecutePropertyGettersAndExtendedSetters(t *testing.T) { }) } -func TestBatchCreatePreservesUpstreamErrorOnWire(t *testing.T) { +func TestBatchCreateAddsBaseDiagnosticsToStderrHint(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}}, + Body: map[string]interface{}{ + "code": 800030201, + "msg": "not_found", + "data": map[string]interface{}{"error": map[string]interface{}{ + "message": "The field does not exist.", + "hint": "List fields in the current table.", + "path": "create_records.0.MissingField", + "value": json.Number("9007199254740993"), + "table": map[string]interface{}{"id": "tbl_x", "name": "Orders"}, + }}, + }, }) - 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()) + + 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 || stdout.Len() != 0 { + t.Fatalf("unexpected result: err=%v stdout=%s", err, stdout) } 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"` + OK bool `json:"ok"` + Error map[string]json.RawMessage `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()) + var hint string + if err := json.Unmarshal(wire.Error["hint"], &hint); err != nil { + t.Fatal(err) + } + wantHint := "List fields in the current table.\n" + + `debug_info: path="create_records.0.MissingField";value=9007199254740993;table={"id":"tbl_x","name":"Orders"}` + if wire.OK || string(wire.Error["code"]) != "800030201" || hint != wantHint { + t.Fatalf("unexpected stderr: %s", &stderr) } - want, _ := json.Marshal(detail) - got, _ := json.Marshal(wire.Error.UpstreamError) - if !bytes.Equal(want, got) { - t.Fatalf("upstream error=%s, want=%s", got, want) + if _, exists := wire.Error["upstream_error"]; exists { + t.Fatalf("unexpected upstream_error field: %s", &stderr) } } diff --git a/shortcuts/base/base_role_common.go b/shortcuts/base/base_role_common.go index 137ffb3fd1..d7a510b14e 100644 --- a/shortcuts/base/base_role_common.go +++ b/shortcuts/base/base_role_common.go @@ -19,9 +19,8 @@ import ( // // The data field may be a JSON object (actual behavior) or a JSON string (per doc). func handleRoleAPIResponse(runtime *common.RuntimeContext, apiResp *larkcore.ApiResp, action string) error { - if _, err := runtime.ClassifyAPIResponse(apiResp); err != nil { - enriched := enrichBaseAPIErrorFromBody(err, apiResp.RawBody, runtime.APIClassifyContext()) - return prefixRoleActionError(enriched, action) + if err := classifyBaseAPIResponse(runtime, apiResp); err != nil { + return prefixRoleActionError(err, action) } return handleRoleResponse(runtime, apiResp.RawBody, action) } diff --git a/shortcuts/base/helpers.go b/shortcuts/base/helpers.go index 379d57e3fb..e4794c0a66 100644 --- a/shortcuts/base/helpers.go +++ b/shortcuts/base/helpers.go @@ -419,11 +419,8 @@ func baseV3RawContext(ctx context.Context, runtime *common.RuntimeContext, metho if err != nil { return nil, baseAPIBoundaryError(err, "API call failed") } - if _, err := runtime.ClassifyAPIResponse(resp); err != nil { - if statusErr := baseHTTPStatusErrorFromInvalidResponse(resp, err); statusErr != nil { - return nil, statusErr - } - return nil, enrichBaseAPIErrorFromBody(err, resp.RawBody, runtime.APIClassifyContext()) + if err := classifyBaseAPIResponse(runtime, resp); err != nil { + return nil, err } result, parseErr := decodeBaseV3Response(resp.RawBody) if parseErr != nil { From 8249e66fa630ff241cb9c92a4c51631e23feda31 Mon Sep 17 00:00:00 2001 From: zgz2048 Date: Thu, 5 Nov 2026 16:15:48 +0800 Subject: [PATCH 5/5] fix(base): preserve scoped permission recovery hints --- shortcuts/base/base_errors.go | 5 +++- shortcuts/base/base_execute_test.go | 44 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/shortcuts/base/base_errors.go b/shortcuts/base/base_errors.go index 83226fbc2d..85f51f687a 100644 --- a/shortcuts/base/base_errors.go +++ b/shortcuts/base/base_errors.go @@ -199,7 +199,10 @@ func baseAPIErrorFromResult(resultMap map[string]interface{}, cc errclass.Classi if hint, _ := detail["hint"].(string); strings.TrimSpace(hint) != "" { p.Hint = strings.TrimSpace(hint) } - p.Hint = appendBaseDebugInfo(p.Hint, detail) + // The presenter matches canonical permission hints before adding command scopes. + if p.Category != errs.CategoryAuthorization { + p.Hint = appendBaseDebugInfo(p.Hint, detail) + } } return err } diff --git a/shortcuts/base/base_execute_test.go b/shortcuts/base/base_execute_test.go index 6cea01873c..49adc94961 100644 --- a/shortcuts/base/base_execute_test.go +++ b/shortcuts/base/base_execute_test.go @@ -4878,3 +4878,47 @@ func TestBatchCreateAddsBaseDiagnosticsToStderrHint(t *testing.T) { t.Fatalf("unexpected upstream_error field: %s", &stderr) } } + +func TestBatchCreatePermissionHintUsesDeclaredScope(t *testing.T) { + t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) + factory, stdout, reg := newExecuteFactory(t) + reg.Register(&httpmock.Stub{ + Method: "POST", URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_create", + RawBody: []byte(`{"code":99991679,"msg":"missing scope","data":{"error":{"type":"permission_denied","retryable":false,"path":"create_records"}}}`), + }) + err := runShortcutWithAuthTypes(t, BaseRecordBatchCreate, nil, []string{ + "+record-batch-create", "--as", "user", "--base-token", "app_x", "--table-id", "tbl_x", + "--json", `{"create_records":[{"Name":"value"}]}`, + }, factory, stdout) + var permission *errs.PermissionError + if !errors.As(err, &permission) || permission.Code != 99991679 || len(permission.MissingScopes) != 0 { + t.Fatalf("expected server permission error without scope details, got %+v (%v)", permission, err) + } + for _, tc := range []struct { + name string + states map[surface.CommandID]surface.CommandState + want string + }{ + {"login visible", nil, `auth login --scope "base:record:create"`}, + {"login hidden", map[surface.CommandID]surface.CommandState{surface.CommandAuthLogin: surface.CommandConcealed}, + "current command requires scope(s): base:record:create"}, + } { + t.Run(tc.name, func(t *testing.T) { + plan := surface.NewPlan(tc.states) + presented := factory.PresentError(err, cmdutil.ErrorPresentationOptions{ + Projector: recovery.NewProjector(func() *surface.Plan { return plan }), + Identity: core.AsUser, + DeclaredScopes: func() []string { + return BaseRecordBatchCreate.DeclaredScopesForIdentity("user") + }, + }) + p, ok := errs.ProblemOf(presented) + if !ok { + t.Fatalf("expected typed presented error, got %v", presented) + } + if !strings.Contains(p.Hint, tc.want) || strings.Contains(p.Hint, "--recommend") || strings.Contains(p.Hint, "debug_info") { + t.Fatalf("hint=%q, want scoped recovery %q", p.Hint, tc.want) + } + }) + } +}