Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
109 changes: 66 additions & 43 deletions shortcuts/base/base_errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,20 @@
package base

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) {
Expand Down Expand Up @@ -150,27 +155,78 @@ 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")
}
if msg := extractDataErrorMessage(resultMap); msg != "" {
resultMap["msg"] = msg
data, _ := resultMap["data"].(map[string]interface{})
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
}
}
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
}
if p, ok := errs.ProblemOf(err); ok && hint != "" {
p.Hint = hint
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 len(fields) == 0 {
return hint
}
debug := "debug_info: " + strings.Join(fields, ";")
if hint == "" {
return debug
}
return hint + "\n" + debug
}

func enrichBaseAPIErrorFromBody(err error, body []byte, cc errclass.ClassifyContext) error {
if _, ok := errs.ProblemOf(err); !ok {
return err
Expand Down Expand Up @@ -221,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
Expand Down
37 changes: 23 additions & 14 deletions shortcuts/base/base_errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,6 @@ import (
"github.com/larksuite/cli/internal/errclass"
)

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)
Expand Down Expand Up @@ -85,14 +72,36 @@ 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" {
t.Fatalf("logID=%q", p.LogID)
}
}

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,
Expand Down
49 changes: 49 additions & 0 deletions shortcuts/base/base_execute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4829,3 +4829,52 @@ func TestBaseViewExecutePropertyGettersAndExtendedSetters(t *testing.T) {
}
})
}

func TestBatchCreateAddsBaseDiagnosticsToStderrHint(t *testing.T) {
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",
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 || 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 map[string]json.RawMessage `json:"error"`
}
if err := json.Unmarshal(stderr.Bytes(), &wire); err != nil {
t.Fatal(err)
}
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)
}
if _, exists := wire.Error["upstream_error"]; exists {
t.Fatalf("unexpected upstream_error field: %s", &stderr)
}
}
5 changes: 2 additions & 3 deletions shortcuts/base/base_role_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
7 changes: 2 additions & 5 deletions shortcuts/base/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading