Custom Exception not being catch python-FastAPI
See original GitHub issueI 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:
- Created 3 years ago
- Reactions:1
- Comments:8 (3 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Your code seems to do exactly what you want already?
@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.