原因:公开错误层将平台并发限流误标为上游限流,并把多种上游 4xx 统一压成 400,影响定位和客户端处理。 影响:新增公开错误 source,平台限流使用 gateway_rate_limited,上游请求按安全分类返回对应状态;数据库与管理端继续保留原始错误码、消息和状态用于审计。 验证:Go 全量测试、pnpm test、pnpm lint、pnpm build、pnpm openapi、gofmt 和 diff 检查均通过。
63 lines
2.0 KiB
Go
63 lines
2.0 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/easyai/easyai-ai-gateway/apps/api/internal/publicerror"
|
|
)
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, message string, codes ...string) {
|
|
writeErrorWithDetails(w, status, message, nil, codes...)
|
|
}
|
|
|
|
func writeErrorWithDetails(w http.ResponseWriter, status int, message string, details map[string]any, codes ...string) {
|
|
code := ""
|
|
if len(codes) > 0 {
|
|
code = strings.TrimSpace(codes[0])
|
|
}
|
|
standard := publicerror.FromFields(code, message, status, status == http.StatusRequestTimeout || status == http.StatusTooManyRequests || status >= 500)
|
|
standard = publicErrorWithRetryAfter(standard, details)
|
|
publicerror.Observe(standard)
|
|
status = standard.HTTPStatus
|
|
errorPayload := map[string]any{
|
|
"message": standard.Message,
|
|
"status": status,
|
|
"code": standard.Code,
|
|
"category": standard.Category,
|
|
"source": standard.Source,
|
|
"httpStatus": standard.HTTPStatus,
|
|
"retryable": standard.Retryable,
|
|
"action": standard.Action,
|
|
"version": standard.Version,
|
|
}
|
|
if standard.Code == "invalid_parameter" || standard.Code == "unsupported_response_parameter" {
|
|
errorPayload["type"] = "invalid_request_error"
|
|
if _, ok := details["param"]; !ok {
|
|
errorPayload["param"] = nil
|
|
}
|
|
}
|
|
for key, value := range safePublicErrorDetails(details, standard, false) {
|
|
errorPayload[key] = value
|
|
}
|
|
writeJSON(w, status, map[string]any{"error": errorPayload})
|
|
}
|
|
|
|
func writeLocalUserRequired(w http.ResponseWriter) {
|
|
writeError(w, http.StatusForbidden, "该账号尚未开通 EasyAI Gateway", errorCodeGatewayUserNotProvisioned)
|
|
}
|
|
|
|
func sendSSE(w http.ResponseWriter, event string, payload any) {
|
|
bytes, _ := json.Marshal(payload)
|
|
_, _ = fmt.Fprintf(w, "event: %s\n", event)
|
|
_, _ = fmt.Fprintf(w, "data: %s\n\n", bytes)
|
|
}
|