question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom Exception not being catch python-FastAPI

See original GitHub issue

I am using FastAPI version 0.52.0. I am trying to raise Custom Exception from a file which is not being catch by exception handler. I am also using middleware. Below are the code snippets Custom Exception class

class CustomException(Exception):
    def __init__(self, code: int, message: str):
        self.code = code
        self.message = message

endpoint

@app.put("/check")
def check(user_data: UserData):
    start = time.time()
    PutUserData().process(user_data)
    print('\n'.join([
        "Web Method Completed",
        f"\tTotal Time: {time.time() - start}"]))
    return JSONResponse(status_code=status.HTTP_201_CREATED, content={"message": "OK"})

Exception Handler

@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
    return JSONResponse(
        status_code=exc.code,
        content={"message": f"Exception Occurred! Reason -> {exc.message}"},
    )

Middleware

@app.middleware("http")
async def add_metric(request: Request, call_next):
    response = await call_next(request)
    print("Response: ", response.status_code)
    return response

I am raising CustomException from PutUserData().process() with custom status code and some message which is not being processed and API is responding with 201 status code. In my use case i would need to raise CustomException with different status code based on situations. Please help me on this.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
Mausecommented, Sep 28, 2020

Your code seems to do exactly what you want already?

import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette import status
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()


class UserData(BaseModel):
    pass


class PutUserData:
    def process(self, user_data):
        raise CustomException(200, 'Whatever')

# your code starts here

class CustomException(Exception):
    def __init__(self, code: int, message: str):
        self.code = code
        self.message = message


@app.put("/check")
def check(user_data: UserData):
    start = time.time()
    PutUserData().process(user_data)
    print('\n'.join(["Web Method Completed", f"\tTotal Time: {time.time() - start}"]))
    return JSONResponse(status_code=status.HTTP_201_CREATED, content={"message": "OK"})


@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
    return JSONResponse(
        status_code=exc.code,
        content={"message": f"Exception Occurred! Reason -> {exc.message}"},
    )


@app.middleware("http")
async def add_metric(request: Request, call_next):
    response = await call_next(request)
    print("Response: ", response.status_code)
    return response

# your code ends here

tc = TestClient(app)

response = tc.put('/check', json={})
assert response.json()['message'].startswith('Exception Occurred!')  # this assertion passes
0reactions
erustusagutucommented, Aug 16, 2021

@wackazong Here’s the discussion on the starlette repo https://github.com/encode/starlette/issues/1175, the Exception class cannot be overridden using the @app.exception_handler decorator.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Handling Errors - FastAPI
When a request contains invalid data, FastAPI internally raises a RequestValidationError . And it also includes a default exception handler for it. To...
Read more >
Catch `Exception` globally in FastAPI - Stack Overflow
However, if I write a custom exception and try to catch it (as shown below), it works just fine. class MyException(Exception): #some code...
Read more >
3 Ways to Handle Errors in FastAPI That You Need to Know
1. HTTPException # · 2. Create a Custom Exception # · 3. Overriding HTTPException #.
Read more >
How to Add Exception Monitoring to FastAPI - Honeybadger.io
Getting access to the official Python APIs is as easy as installing ... us that the exception is not being sent to the...
Read more >
The Ultimate FastAPI Tutorial Part 5 - Basic Error Handling
We import the HTTPException from FastAPI · Where no recipe is found, we raise an HTTPException passing in a status_code of 404, which...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found