Fastapi: [QUESTION] How to make Fastapi put the stacktrace in the body when handling 500 error

Created on 11 Apr 2020  路  8Comments  路  Source: tiangolo/fastapi

First check

  • [x] I used the GitHub search to find a similar issue and didn't find it.
  • [x] I searched the FastAPI documentation, with the integrated search.
  • [x] I already searched in Google "How to X in FastAPI" and didn't find any information.

Description

During the development cycle, especially when running on a remote machine (QA environment etc.) it's pretty convenient to have the traceback directly in the body of a 500 response so that one does not have to connect to the machine to get the traceback.

Of course it's something that one should opt-in , as you don't want to have that in production

question

Most helpful comment

Starlette has a built-in server exception middleware - use FastAPI(debug=True) to enable it

All 8 comments

You could start with https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers with a call to a function in traceback module.

ah yeah right , stupid me, thanks for the pointer, I will try to come up with something and put it here in case somebody wonders the same thing

ok I've hacked this and it seems to work pretty well

if DISPLAY_TRACEBACK_ON_500:

    @app.exception_handler(Exception)
    async def debug_exception_handler(request: Request, exc: Exception):
        import traceback

        return Response(
            content="".join(
                traceback.format_exception(
                    etype=type(exc), value=exc, tb=exc.__traceback__
                )
            )
        )


You may want to close the issue if it works for you :)

haha sure

Thanks for the help here @phy25 ! :cake: :bow:

Thanks @allan-simon for coming back to close it :+1:

Starlette has a built-in server exception middleware - use FastAPI(debug=True) to enable it

Starlette has a built-in server exception middleware - use FastAPI(debug=True) to enable it

The fact that you can set debug=true is mentioned in several places, but not where to or how to. I finally saw your reply after 2hrs of googling. Would be great to get this into the fastapi docs.

Was this page helpful?
0 / 5 - 0 ratings