Maku
Maku

Reputation: 1610

What's the best way to display Exception in Flask?

I'm a newbie in Flask and I am trying to display the Built-In Exceptions in python but I can't seem to have them display on my end.

NOTE:

set FLASK_DEBUG = 0

CODE:

def do_something:
    try:
        doing_something()
    except Exception as err:
        return f"{err}"

Expectation:

Reality:

Also:

Upvotes: 0

Views: 2716

Answers (2)

Julian Camilleri
Julian Camilleri

Reputation: 3105

Flask supplies you with a function that enables you to register an error handler throughout your entire app; you can do something as shown below:

def handle_exceptions(e):
    # Log exception in your logs
    # get traceback and sys exception info and log as required   
    # app.logger.error(getattr(e, 'description', str(e)))

    # Print traceback

    # return your response using getattr(e, 'code', 500) etc. 

# Exception is used to catch all exceptions
app.register_error_handler(Exception, handle_exceptions)

In my honest opinion, this is the way to go. - Following the structure found in werkzeug.exceptions.HTTPException as an example is a solid foundation.

Having a unified exception handler that will standardise your Exception handling, visualisation and logging will make your life a tad better. :)

Upvotes: 2

dteod
dteod

Reputation: 331

Try with this:

def do_something:
    try:
        doing_something()
    except Exception as err:
        return f"{err.__class__.__name__}: {err}"

Upvotes: 3

Related Questions