【问题标题】:Customise Status codes in place of 500: Internal Server Error in FastAPI using Postman自定义状态代码代替 500:使用 Postman 的 FastAPI 中的内部服务器错误
【发布时间】:2021-10-21 10:51:47
【问题描述】:

我在使用 FastAPI 和邮递员方面非常陌生。当我发送带有正文(输入数据)的 POST 请求时,我收到了成功代码 200 以及预期的响应。

现在,我想调整我的输入数据以使我的代码故意失败。这也在发生。但是状态代码将变为 500 并且 Internal Server Error 正在响应中显示。

我想在每种失败情况下手动给出一个状态代码,并在响应中给出一些相关的输出。如何实现这个目标?

【问题讨论】:

标签: fastapi postman-testcase


【解决方案1】:

如果您想要 JSON 响应格式,这可能会有所帮助

from fastapi.responses import JSONResponse
from fastapi import status

def my_function():
    return JSONResponse(
                status_code=500,
                content={
                         "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                         "message": "Internal Server Error"}
            )

【讨论】:

  • 我需要手动提供状态码。这里可以吗?
  • 是的,可能。根据需要更改状态代码。请参阅此列表github.com/encode/starlette/blob/master/starlette/status.py。如果没有找到任何相关的,只需输入手动代码。
  • 好的.. 您能否显示一个状态码为 406 且详细信息为“Solver TimeOut”的实例?
  • 只需更改状态码即可。 JSONResponse( status_code=406, content={ "code": 406 "message": "Solver TimeOut"} )
【解决方案2】:

详细的解决方案可以在https://fastapi.tiangolo.com/tutorial/handling-errors/找到。

一个快速的解决方案是在使用 try 和 except 语句返回输出的函数中添加以下行:

try:
    output
except Exception:
    raise HTTPException(status_code=406, detail="New Error Found")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多