82 行
2.4 KiB
Python
82 行
2.4 KiB
Python
"""Common API response helpers for the v3 contract."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from enum import StrEnum
|
|
from typing import Any
|
|
|
|
|
|
class ErrorCode(StrEnum):
|
|
UNAUTHORIZED = "UNAUTHORIZED"
|
|
FORBIDDEN = "FORBIDDEN"
|
|
VALIDATION_FAILED = "VALIDATION_FAILED"
|
|
RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND"
|
|
CONFIG_REVISION_CONFLICT = "CONFIG_REVISION_CONFLICT"
|
|
TASK_NOT_RETRYABLE = "TASK_NOT_RETRYABLE"
|
|
TASK_NOT_CANCELABLE = "TASK_NOT_CANCELABLE"
|
|
MODEL_CAPABILITY_UNCONFIRMED = "MODEL_CAPABILITY_UNCONFIRMED"
|
|
MODEL_CAPABILITY_UNSUPPORTED = "MODEL_CAPABILITY_UNSUPPORTED"
|
|
STORAGE_WRITE_FAILED = "STORAGE_WRITE_FAILED"
|
|
MEDIA_NOT_FOUND = "MEDIA_NOT_FOUND"
|
|
UPLOAD_TOO_LARGE = "UPLOAD_TOO_LARGE"
|
|
UNSUPPORTED_FILE_TYPE = "UNSUPPORTED_FILE_TYPE"
|
|
INTEGRATION_TOKEN_INVALID = "INTEGRATION_TOKEN_INVALID"
|
|
UNKNOWN_ERROR = "UNKNOWN_ERROR"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ApiError(Exception):
|
|
error_code: ErrorCode
|
|
message: str
|
|
details: dict[str, Any] | None = None
|
|
|
|
def to_response(self, request_id: str | None = None) -> dict[str, Any]:
|
|
return error_response(
|
|
error_code=self.error_code,
|
|
message=self.message,
|
|
details=self.details,
|
|
request_id=request_id,
|
|
)
|
|
|
|
|
|
def success_response(
|
|
data: Any,
|
|
*,
|
|
request_id: str | None = None,
|
|
warnings: list[str] | None = None,
|
|
) -> dict[str, Any]:
|
|
return {
|
|
"ok": True,
|
|
"data": data,
|
|
"warnings": warnings or [],
|
|
"request_id": request_id,
|
|
}
|
|
|
|
|
|
def error_response(
|
|
*,
|
|
error_code: ErrorCode | str,
|
|
message: str,
|
|
details: dict[str, Any] | None = None,
|
|
request_id: str | None = None,
|
|
) -> dict[str, Any]:
|
|
code = error_code.value if isinstance(error_code, ErrorCode) else error_code
|
|
return {
|
|
"ok": False,
|
|
"error_code": code,
|
|
"message": message,
|
|
"details": details or {},
|
|
"request_id": request_id,
|
|
}
|
|
|
|
|
|
def response_from_exception(exc: Exception, request_id: str | None = None) -> dict[str, Any]:
|
|
if isinstance(exc, ApiError):
|
|
return exc.to_response(request_id=request_id)
|
|
return error_response(
|
|
error_code=ErrorCode.UNKNOWN_ERROR,
|
|
message="\u670d\u52a1\u5668\u5185\u90e8\u9519\u8bef",
|
|
details={"exception": exc.__class__.__name__},
|
|
request_id=request_id,
|
|
)
|