用全局 handler 统一收口
有了格式,下一步是让所有异常都经过同一个响应转换层,而不是到处手动转换。
前面的示例用的是普通 Exception 子类来表达业务语义,但到了全局 handler 这一层会遇到一个问题:handler 怎么知道该返回什么状态码和错误码?解决方案是设计一个携带这些属性的基类 AppError,用类变量声明每种异常的固定属性:
class AppError(Exception):
status_code: int = 500
code: str = "internal_error"
message: str = "Internal server error"
details: dict | list | None = None
class EmailAlreadyExistsError(AppError):
status_code = 409
code = "email_exists"
message = "Email already exists"
class PostArchivedError(AppError):
status_code = 400
code = "post_archived"
message = "Archived post cannot be updated"
然后注册全局 handler,分别处理业务异常和 HTTPException,但最终都转换成同一个 ErrorResponse: