{"id":908,"hash":"d236f9f4b60f9ba3c2c62df83a6dbb3ac5839c6900557f7e9f9d352437e72b8c","pattern":"Catch `Exception` globally in FastAPI","full_message":"I am trying to catch unhandled exceptions at global level. So somewhere in main.py file I have the below:\n\n@app.exception_handler(Exception)\nasync def exception_callback(request: Request, exc: Exception):\n  logger.error(exc.detail)\n\nBut the above method is never executed. However, if I write a custom exception and try to catch it (as shown below), it works just fine.\n\nclass MyException(Exception):\n  #some code\n\n@app.exception_handler(MyException)\nasync def exception_callback(request: Request, exc: MyException):\n  logger.error(exc.detail)\n\nI have gone through Catch exception type of Exception and process body request #575. But this bug talks about accessing request body. After seeing this bug, I feel it should be possible to catch Exception.\nFastAPI version I am using is: fastapi>=0.52.0.\n\nThanks in advance :)\n\nUpdate\nThere are multiple answers, I am thankful to all the readers and authors here.\nI was revisiting this solution in my application. Now I see that I needed to set debug=False, default it's False, but I had it set to True in\n\nserver = FastAPI(\n    title=app_settings.PROJECT_NAME,\n    version=app_settings.VERSION,\n)\n\nIt seems that I missed it when @iedmrc commented on answer given by @Kavindu Dodanduwa.","ecosystem":"pypi","package_name":"python-3.x","package_version":null,"solution":"In case you want to capture all unhandled exceptions (internal server error), there's a very simple way of doing it. Documentation\n\nfrom fastapi import FastAPI\nfrom starlette.requests import Request\nfrom starlette.responses import Response\nfrom traceback import print_exception\n\napp = FastAPI()\n\nasync def catch_exceptions_middleware(request: Request, call_next):\n    try:\n        return await call_next(request)\n    except Exception:\n        # you probably want some kind of logging here\n        print_exception(e)\n        return Response(\"Internal server error\", status_code=500)\n\napp.middleware('http')(catch_exceptions_middleware)\n\nMake sure you place this middleware before everything else.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/61596911/catch-exception-globally-in-fastapi","votes":59,"created_at":"2026-04-19T04:51:59.333072+00:00","updated_at":"2026-04-19T04:51:59.333072+00:00"}