FastAPI not raising HTTPException

2.9k views Asked by At

I'm trying to raise an exception in FastAPI when an object with a specific key already exists (e.g. RethinkDb return "Duplicated key" error). Probably something wrong with my method logic, but can't get what exactly.

@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)
1

There are 1 answers

0
Yagiz Degirmenci On BEST ANSWER

You have a try-catch and it captures all the errors that occured. You are just capturing your own Exception which is isn't actually been raised yet.

@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

This should be working fine.