[Fixed]-Django exception handler for the default-brench in try-except block

1👍

By using a return statement in the finally block, you’re effectively hiding the error. Usually any uncaught exception is reraised after the finally block, but the return statement returns control from the function before this can happen. It’s better to move the return statement out of the finally block and let the unexpected error propagate naturally:

def test_view():
    try
        # some code block
    except error_type_1:
        status = 428
        # do something
    except error_type_2:
        # do something else

    return smth

You can catch all exceptions with a bare except clause or by catching Exception, though this is often not recommended, as it can easily hide the details needed to debug the problem:

try:
    do_something()
except:
    handle_exception()

try:
    do_something()
except Exception as exc:
    handle_exception(exc)

When a view function raises an exception, Django will do this for you and give you a detailed error page, which includes the error message, traceback, local variables and more.

👤knbk

Leave a comment