Skip to content

Error Handling

Error Handling

Python
from fastapi import HTTPException
from pymongo.errors import DuplicateKeyError
from bson.errors import InvalidId

@app.post("/users/")
async def create_user(user: User):
    try:
        return await user_repo.create(user)
    except DuplicateKeyError:
        raise HTTPException(status_code=409, detail="User already exists")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/users/{user_id}")
async def get_user(user_id: str):
    try:
        user = await user_repo.get_by_id(user_id)
        if not user:
            raise HTTPException(status_code=404, detail="User not found")
        return user
    except InvalidId:
        raise HTTPException(status_code=400, detail="Invalid user ID format")