0

I'm writing an error handler for the RequestEntityTooLarge exception in Flask such that the exception can be caught when it's raised in any views. I'd like to handle the exception by flashing a message on top of the page where it's raised.

Below is what I have so far, is there a way I can get the view where the exception is raised so I can re-render it?

@app.errorhandler(413)
def request_entity_too_large(error):
    flash("File too large", "error-box")
    return render_template(...) // it should re-render the view where exception is raised

Since Flask throws this exception automatically, I think try/catch blocks with custom exception class can be helpful here, I'm curious if there're other easier way to achieve this.

liyche
  • 21
  • 4

1 Answers1

0

You can throw the exception using the abort function.

from flask import abort

@app.route('/something')
def something():
    if (error_occur):
        abort(413)
    else:
        something_else()


@app.errorhandler(413)
def custom_error(error):
    return render_template('413.html'), 413

Inside your HTML template file, you can display that flash message.

Aditya Naitan
  • 162
  • 3
  • 11
  • Thanks for your time, but this is not what I'm looking for. I'm not using a custom error page. I need the '413.html' to be a variable so it can render the same view where abort(413) is called, and abort(413) will be called in different views. I ended up using a try/except block and error.description to achieve what I wanted from this [post](https://stackoverflow.com/questions/21294889/how-to-get-access-to-error-message-from-abort-command-when-using-custom-error-ha) – liyche Jul 07 '22 at 16:43