用途:在定义 API 错误契约、把领域失败映射为 HTTP 响应时使用本技能。
主要能力:定义预期失败类别的领域异常;将异常全局或按作用域映射到 Litestar 处理器;返回一致的错误载荷结构;记录足够调试上下文而不泄露敏感信息。
使用方式:定义领域异常类,编写处理器函数,并在 Litestar 应用初始化时通过 exception_handlers 参数注册映射。示例:
from litestar import Litestar, Request from litestar.response import Response
class DomainError(Exception): pass
def domain_error_handler(_: Request, __: DomainError) -> Response[dict[str, str]]: return Response({"error": "domain_error"}, status_code=400)
app = Litestar( route_handlers=[], exception_handlers={DomainError: domain_error_handler}, )
检查清单:区分客户端错误(4xx)与服务端错误(5xx);保持载荷结构稳定(code、message、可选 details);为每种预期失败模式配套测试。
参考:https://docs.litestar.dev/latest/usage/exceptions.html
限制:资料未提供具体版本要求、安装命令、收费信息或平台支持范围。