how do i handle fastapi errors with sentry?

Viewed 1288

i have the following function that i am trying to handle the errors for and send them to sentry

import sentry_sdk
...
...
...
def create_orders(
    orders: orders_schema.OrderCreate
):
    try:
        query = "INSERT INTO orders VALUES (nextval('orders_id_seq'), :price, :currency, :created_on, :note)"
        values = {
            "price": orders.price,
            "currency": orders.currency,
            "created_on": datetime.utcnow(),
            "note": orders.note
        }
    except Exception as err:
        sentry_sdk.capture_exception(err)
    return database.execute(query, values=values)

here is the router endpoint calling the function

@router.post("/orders/create", response_model=orders_schema.OrderCreate)
async def create_new_order(
    orders: orders_schema.OrderCreate
):

    await crud.create_orders(orders)
    return {**orders.dict()}

Sentry integration works as i have tested receiving some other unhandled error event, but now i want to actually use sentry for what i need it for; which is to help manage handled errors

but when i try to send wrong values or wrong key to the api endpoint, nothing is sent to sentry

am i missing something or what do i do to be able to send the errors?

3 Answers

the line that captures the error for sentry is probably never being executed, since the access to the DB is on the return statement... in other words, what you have in the try/except block is not failing, so the except doesn't run, then the code goes to the return line where probably is failing for you, but at that point sentry is not longer catching it

def create_orders(
    orders: orders_schema.OrderCreate
):
    try:
        result = None
        query = "INSERT INTO orders VALUES (nextval('orders_id_seq'), :price, :currency, :created_on, :note)"
        values = {
            "price": orders.price,
            "currency": orders.currency,
            "created_on": datetime.utcnow(),
            "note": orders.note
        }
        result = database.execute(query, values=values)
    except Exception as err:
        sentry_sdk.capture_exception(err)
    finally:
        return result

You can just raise the error:

from fastapi import FastAPI, HTTPException
@router.post("/orders/create", response_model=orders_schema.OrderCreate)
async def create_new_order(orders: orders_schema.OrderCreate):
try:
    await crud.create_orders(orders)
    return {**orders.dict()
except Exception as e:
   raise HTTPException(status_code=404,detail=e)
Related