我正在 uvicorn 下运行一个简单的 FastAPI 应用程序。 FastAPI代码是这样的:
from fastapi import FastAPI
@app.post("/events")
def create_events():
print("entering create_events()")
raise Exception("an error")
我运行应用程序:
uvicorn api.main:app --reload --log-level=debug
我现在使用 wget 发布到端点:
wget -O- --header='Content-Type:application/json' --post-file=/tmp/data.json http://127.0.0.1:8000/events
毫不奇怪,wget 返回 500 内部服务器错误。
在我运行 uvicorn 的终端的输出中,我看到了这个:
entering create_events()
在其他 Web 应用程序上下文(Perl、Ruby on Rails、Python with Flask)中,如果服务器引发未处理的异常,我可以在服务器端某处看到错误消息:在日志文件中、在标准输出上、某处。但在这个 FastAPI/uvicorn 应用程序中,我找不到任何错误消息。我在运行 wget 的地方没有看到它,在 uvicorn 终端中也没有看到它。
500 错误消息记录/显示在哪里?
如果您希望 Fastapi 端点返回特定的 Http 错误,您需要使用
HTTPException
。如果端点执行的代码抛出任何其他异常,它将返回 500,这是内部服务器错误。
示例:
from fastapi import FastAPI, HTTPException, status
@app.post("/events")
def create_events():
print("entering create_events()")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="an error",
)
如果您想记录错误消息,您可以添加自定义处理程序:
from fastapi import Request
from fastapi.responses import PlainTextResponse
async def unhandled_exception_handler(request: Request, exc: Exception) -> PlainTextResponse:
"""
This middleware will log all unhandled exceptions.
Unhandled exceptions are all exceptions that are not HTTPExceptions or RequestValidationErrors.
"""
logger.debug("Our custom unhandled_exception_handler was called")
host = getattr(getattr(request, "client", None), "host", None)
port = getattr(getattr(request, "client", None), "port", None)
url = f"{request.url.path}?{request.query_params}" if request.query_params else request.url.path
exception_type, exception_value, exception_traceback = sys.exc_info()
exception_name = getattr(exception_type, "__name__", None)
logger.error(
f'{host}:{port} - "{request.method} {url}" 500 Internal Server Error <{exception_name}: {exception_value}>'
)
return PlainTextResponse(str(exc), status_code=500)
然后您可以将处理程序添加到您的应用程序中:
app.add_exception_handler(Exception, unhandled_exception_handler)