starlette 通过注册自定义异常处理器(exception handlers)来统一处理异常并返回 json 错误信息。开发者需要在应用实例上调用 add_exception_handler 方法,将特定的异常类映射到对应的异步处理函数中,这些函数接收请求和异常实例作为参数,并返回标准的 jsonresponse 对象。

如何注册全局异常处理器
要捕获所有未处理的异常并返回统一的 JSON 格式,可以注册一个针对 Exception 基类的处理器。该处理器会拦截所有未被其他特定处理器捕获的异常,确保 API 始终返回结构化的错误响应,而不是默认的 HTML 调试页面。

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
import traceback
async def homepage(request):
return JSONResponse({"hello": "world"})
async def error_handler(request, exc):
# 记录详细的堆栈信息以便调试
print(traceback.format_exc())
# 返回标准的 JSON 错误响应
return JSONResponse(
status_code=500,
content={"detail": str(exc)}
)
app = Starlette(
routes=[Route("/", homepage)],
)
# 注册全局异常处理器
app.add_exception_handler(Exception, error_handler)
运行上述代码后,访问根路径将返回正常数据。如果修改 homepage 使其抛出异常(如 raise ValueError("test")),客户端将收到状态码为 500 且包含 detail 字段的 JSON 响应。
如何注册特定类型的异常处理器
除了全局处理器,还可以为特定的异常类型注册专门的处理器,例如 HTTPException。这种方式允许针对不同错误场景返回不同的 HTTP 状态码和错误详情,提供更精细的错误控制。
一个基于官方 Mailtrap Node.js SDK 构建的 ASE 技能,用于发送事务邮件并与 Mailtrap 沙盒或生产流程协作。它非常适合需要 API 驱动邮件投递、测试邮箱验证和结构化消息自动化的代理工作流。

from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse
async def http_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail}
)
app.add_exception_handler(HTTPException, http_exception_handler)
async def raise_error(request):
raise HTTPException(status_code=404, detail="Not Found")
app.routes.append(Route("/error", raise_error))
当访问 /error 端点时,程序会抛出 HTTPException。由于已注册特定处理器,客户端将收到状态码为 404 且内容为 {"detail": "Not Found"} 的 JSON 响应,而不是通用的 500 错误。
如何处理自定义业务异常
在实际开发中,通常需要定义自己的业务异常类,以便在业务逻辑中抛出具有特定语义的错误。通过将这些自定义异常类注册到异常处理器中,可以实现更清晰的错误分类和处理逻辑。
class CustomBusinessError(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
super().__init__(self.message)
async def custom_error_handler(request, exc):
return JSONResponse(
status_code=400,
content={
"error_code": exc.code,
"message": exc.message
}
)
app.add_exception_handler(CustomBusinessError, custom_error_handler)
async def trigger_custom_error(request):
raise CustomBusinessError(message="Invalid input", code=1001)
app.routes.append(Route("/custom", trigger_custom_error))
访问 /custom 端点时,程序会抛出 CustomBusinessError。注册的处理器会捕获该异常,并返回包含 error_code 和 message 字段的 JSON 响应,状态码固定为 400。这种机制使得前端可以根据 error_code 进行具体的业务逻辑处理。










