我目前正在fastAPI中为一个API编写一些端点。我正在定义扩展fastapi的HTTPException的类。
问题是HTTPException返回一个响应主体,其中包含一个名为detail的属性,该属性将是一个字符串或JSON结构,具体取决于您传递给它的对象,如下所示。
{
"detail": {
"msg": "error message here"
}
}
{ "detail": "error message here" }
我想覆盖这个行为,让它用我自己的结构来响应。
我知道我可以使用异常处理程序装饰器安装自定义异常,并使其返回JSONResponse对象,但这不是我要找的。
2条答案
按热度按时间ljo96ir51#
一个选项是set the status code对应于您的异常,然后返回一个自定义的响应体。
下面是一个简单的玩具示例,使用这种方法来解决手头的问题:
可用状态代码的完整列表可在here中找到。
nx7onnlm2#
建议使用FastAPI提供的状态模块,而不是直接使用数字HTTP状态代码。这种方法提高了代码的可读性并降低了出错的可能性。