49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
"""统一错误码与领域异常(ARCH §7.1)。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from enum import StrEnum
|
||
|
||
|
||
class ErrorCode(StrEnum):
|
||
NOT_FOUND = "NOT_FOUND"
|
||
VALIDATION = "VALIDATION"
|
||
CONFLICT = "CONFLICT" # 资源状态冲突(如对非 awaiting 链 job 续跑)
|
||
CONFLICT_UNRESOLVED = "CONFLICT_UNRESOLVED" # 未决冲突禁验收
|
||
LLM_UNAVAILABLE = "LLM_UNAVAILABLE" # 回退耗尽
|
||
RATE_LIMITED = "RATE_LIMITED"
|
||
PAYLOAD_TOO_LARGE = "PAYLOAD_TOO_LARGE" # 请求体超过大小上限(body-size 中间件)
|
||
INTERNAL = "INTERNAL"
|
||
|
||
|
||
# 错误码 -> HTTP 状态
|
||
HTTP_STATUS: dict[ErrorCode, int] = {
|
||
ErrorCode.NOT_FOUND: 404,
|
||
ErrorCode.VALIDATION: 422,
|
||
ErrorCode.CONFLICT: 409,
|
||
ErrorCode.CONFLICT_UNRESOLVED: 409,
|
||
ErrorCode.LLM_UNAVAILABLE: 503,
|
||
ErrorCode.RATE_LIMITED: 429,
|
||
ErrorCode.PAYLOAD_TOO_LARGE: 413,
|
||
ErrorCode.INTERNAL: 500,
|
||
}
|
||
|
||
|
||
class AppError(Exception):
|
||
"""领域异常:在边界处映射为统一错误信封。"""
|
||
|
||
def __init__(
|
||
self,
|
||
code: ErrorCode,
|
||
message: str,
|
||
details: dict[str, object] | None = None,
|
||
) -> None:
|
||
super().__init__(message)
|
||
self.code = code
|
||
self.message = message
|
||
self.details = details or {}
|
||
|
||
@property
|
||
def http_status(self) -> int:
|
||
return HTTP_STATUS.get(self.code, 500)
|