API契约:迁移聊天商品与自动化错误
This commit is contained in:
1 parent
4d92e8e919
commit
82da4d8bb5
8 files changed
+134
-29
No files matched your search
@@ -37,6 +37,8 @@ type ErrorResponse struct {
|
||||
Message string `json:"message"`
|
||||
// RequestID 是可选的请求追踪标识,便于服务端日志关联。
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
// Details 是仅供恢复或审计使用的结构化附加信息,不承载错误判定逻辑。
|
||||
Details map[string]any `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// CodeForStatus 将 HTTP 状态码映射为稳定的通用错误码。
|
||||
@@ -67,8 +69,13 @@ func CodeForStatus(status int) string {
|
||||
|
||||
// WriteError 使用统一的 code、message 和可选 request_id 写入 JSON 错误响应。
|
||||
func WriteError(w http.ResponseWriter, status int, code, message, requestID string) {
|
||||
WriteErrorDetails(w, status, code, message, requestID, nil)
|
||||
}
|
||||
|
||||
// WriteErrorDetails 使用统一错误字段和可选附加详情写入 JSON 错误响应。
|
||||
func WriteErrorDetails(w http.ResponseWriter, status int, code, message, requestID string, details map[string]any) {
|
||||
// response 是本次请求要序列化的统一错误 DTO。
|
||||
response := ErrorResponse{Code: code, Message: message, RequestID: requestID}
|
||||
response := ErrorResponse{Code: code, Message: message, RequestID: requestID, Details: details}
|
||||
if response.Code == "" {
|
||||
response.Code = CodeForStatus(status)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestWriteErrorDetails 验证统一错误 DTO 可携带恢复所需的结构化详情。
|
||||
func TestWriteErrorDetails(t *testing.T) {
|
||||
// recorder 是捕获错误响应的测试记录器。
|
||||
recorder := httptest.NewRecorder()
|
||||
// details 是远端操作完成后供客户端核对的商品信息。
|
||||
details := map[string]any{"item_id": "remote-item", "item_url": "https://example/item/remote-item"}
|
||||
WriteErrorDetails(recorder, http.StatusInternalServerError, "remote_published_local_save_failed", "本地保存失败", "req-1", details)
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
// response 是反序列化后的统一错误 DTO。
|
||||
var response ErrorResponse
|
||||
// decodeErr 表示错误响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode error response: %v", decodeErr)
|
||||
}
|
||||
if response.Code != "remote_published_local_save_failed" || response.Message != "本地保存失败" || response.RequestID != "req-1" {
|
||||
t.Fatalf("response=%+v", response)
|
||||
}
|
||||
if response.Details["item_id"] != "remote-item" || response.Details["item_url"] != "https://example/item/remote-item" {
|
||||
t.Fatalf("details=%+v", response.Details)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user