首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FastAPI未引发HTTPException

FastAPI未引发HTTPException
EN

Stack Overflow用户
提问于 2020-09-28 20:39:07
回答 1查看 724关注 0票数 1

当具有特定键的对象已经存在时(例如,RethinkDb返回"Duplicated“错误),我试图在FastAPI中引发异常。可能是我的方法逻辑出了问题,但是不能得到确切的结果。

代码语言:javascript
复制
@router.post("/brands", response_model=Brand, status_code=status.HTTP_201_CREATED)
def add_brand(brand: Brand):
    with r.connect('localhost', 28015, 'expressparts').repl() as conn:
        try:
            result = r.table("brands").insert({
                "id": brand.id,
                "name": brand.name}).run(conn)
            if result['errors'] > 0:
                error = result['first_error'].split(":")[0]
                raise HTTPException(
                    status_code=400, detail=f"Error raised: {error}")
            else:
                return brand
        except Exception as err:
            print(err)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-28 21:05:46

您有一个try-catch,它捕获所有发生的错误。您只是捕获了您自己的异常,实际上它还没有被引发。

代码语言:javascript
复制
@router.post("/brands", response_model=Brand, status_code=status.HTTP_201_CREATED)
def add_brand(brand: Brand):
    with r.connect('localhost', 28015, 'expressparts').repl() as conn:
        result = r.table("brands").insert({
            "id": brand.id,
            "name": brand.name}).run(conn)
        if result['errors'] > 0:
            error = result['first_error'].split(":")[0]
            raise HTTPException(
                status_code=400, detail=f"Error raised: {error}")
        else:
            return brand

这应该可以很好地工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64102371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档