File size: 6,024 Bytes
36fae79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44132c4
 
36fae79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44132c4
36fae79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44132c4
 
36fae79
 
 
 
 
 
 
 
44132c4
36fae79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44132c4
36fae79
 
 
 
 
 
 
 
 
44132c4
36fae79
 
 
 
44132c4
 
 
 
 
 
 
 
36fae79
44132c4
 
 
 
 
 
36fae79
 
44132c4
36fae79
 
44132c4
36fae79
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""统一错误模型。

完全兼容原 Netlify 版返回格式:
    { "ok": false, "error": { "code", "message", "status", "retryable", "hint", "upstream?", "details?" } }

错误码集合:bad_request/unauthorized/forbidden/not_found/request_timeout/
quota_exceeded/internal_error/service_unavailable/upstream_timeout/
model_disabled/server_misconfigured
"""
from __future__ import annotations

from typing import Any, Optional

from fastapi import Request
from fastapi.responses import JSONResponse

from .cors import build_cors_headers


# 状态码 -> 错误码
_STATUS_TO_CODE = {
    400: "bad_request",
    401: "unauthorized",
    402: "payment_required",
    403: "forbidden",
    404: "not_found",
    405: "method_not_allowed",
    408: "request_timeout",
    409: "conflict",
    422: "unprocessable_entity",
    429: "quota_exceeded",
    500: "internal_error",
    502: "bad_gateway",
    503: "service_unavailable",
    504: "upstream_timeout",
}

# 可重试状态码
_RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}


class HttpError(Exception):
    """统一 HTTP 异常。"""

    def __init__(
        self,
        message: str,
        status: int = 500,
        code: Optional[str] = None,
        details: Any = None,
        upstream: Any = None,
    ) -> None:
        super().__init__(message)
        self.message = message
        self.status = status
        self.code = code or _STATUS_TO_CODE.get(status, "internal_error")
        self.details = details
        self.upstream = upstream


def error_code_for_status(status: int, fallback: str = "upstream_error") -> str:
    return _STATUS_TO_CODE.get(status, fallback)


def is_retryable_status(status: int) -> bool:
    return status in _RETRYABLE_STATUS


def get_error_hint(*, code: str, status: int, message: str) -> Optional[str]:
    """生成给前端展示的提示文案。"""
    text = (message or "").lower()
    if code == "unauthorized" or status == 401:
        return "请检查 access_key/access_token 是否正确,或先重新生成临时令牌"
    if code == "forbidden" or status == 403:
        return "当前账号或策略不允许此操作,请检查后台厂商与模型策略"
    if code == "not_found" or status == 404:
        return "资源不存在,请检查接口路径、provider 与 model 参数"
    if code == "quota_exceeded" or status == 429:
        return "请求过快或额度不足,建议稍后重试或切换厂商/模型"
    if code == "upstream_timeout" or status == 504 or "timeout" in text:
        return "上游超时,建议降低 max_tokens 或稍后重试"
    if code == "bad_request" or status in (400, 422):
        return "请求参数格式可能有误,请检查 messages/images/model 字段"
    if status >= 500:
        return "服务暂时不可用,请稍后重试"
    return None


def make_error_response(
    *,
    message: str,
    status: int = 500,
    code: Optional[str] = None,
    details: Any = None,
    upstream: Any = None,
    origin: Optional[str] = None,
) -> JSONResponse:
    err_code = code or _STATUS_TO_CODE.get(status, "internal_error")
    hint = get_error_hint(code=err_code, status=status, message=message)
    payload = {
        "ok": False,
        "error": {
            "code": err_code,
            "message": message,
            "status": status,
            "retryable": is_retryable_status(status),
            "hint": hint,
        },
    }
    if details is not None:
        payload["error"]["details"] = details
    if upstream is not None:
        payload["error"]["upstream"] = upstream
    # 动态 CORS:白名单模式下基于 Origin 匹配,未匹配不回 CORS 头
    return JSONResponse(status_code=status, content=payload, headers=build_cors_headers(origin))


def make_upstream_error_response(
    *,
    status: int,
    text: str,
    json_body: Any = None,
    fallback_code: str = "upstream_error",
    origin: Optional[str] = None,
) -> JSONResponse:
    """从上游响应构造统一错误。"""
    upstream_err = None
    if isinstance(json_body, dict):
        upstream_err = json_body.get("error") if isinstance(json_body.get("error"), dict) else json_body
    code = (upstream_err or {}).get("code") if isinstance(upstream_err, dict) else None
    code = code or error_code_for_status(status, fallback_code)
    message = (upstream_err or {}).get("message") if isinstance(upstream_err, dict) else None
    message = message or text or f"Upstream error ({status})"
    hint = get_error_hint(code=code, status=status, message=message)
    payload = {
        "ok": False,
        "error": {
            "code": code,
            "message": message,
            "status": status,
            "retryable": is_retryable_status(status),
            "hint": hint,
            "upstream": upstream_err,
        },
    }
    return JSONResponse(status_code=status, content=payload, headers=build_cors_headers(origin))


async def http_error_handler(request: Request, exc: HttpError) -> JSONResponse:
    return make_error_response(
        message=exc.message,
        status=exc.status,
        code=exc.code,
        details=exc.details,
        upstream=exc.upstream,
        origin=request.headers.get("origin"),
    )


async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """未捕获异常兜底处理。

    安全要点:
    - 完整 traceback 只打到服务端日志,绝不返回给客户端
      (避免泄露内部文件路径、SQL 片段、密钥片段等)
    - 客户端只收到固定文案 ``Unexpected error``,不暴露 str(exc)
    """
    import logging
    import traceback
    logging.getLogger(__name__).error(
        "[unhandled] %s %s -> 500: %s",
        request.method,
        request.url.path,
        exc,
    )
    traceback.print_exc()
    return make_error_response(
        message="Unexpected error",
        status=500,
        code="internal_error",
        origin=request.headers.get("origin"),
    )