2

On my website, I want to be able to give the user better feedback on a 404 error than "page not found". If a view raises a 404 error, I want to pass an extra parameter to the template that describes what the view shows. For instance:

views.py

def get_or_404(model, attribute, value, template, **kwargs):
    try:
        return session.query(model).filter(attribute == value).one()
    except NoResultFound:
        abort(404)

@app.errorhandler(404)
def page_not_found(error):
    return render_template("404.html"), 404

@app.route("project/<project_id>")
def project_show(project_id):
    """
    Show the files contained in a specific project.

    :param int project_id: The ID of the desired project.
    """

    project = get_or_404(Project, Project.id, project_id, "item_not_found.html", item="project")

    # Other stuff

If the user attempts to go to a project that does not exist, then they are sent to a 404 page. If I can provide the item kwarg (from project_show) to the template 404.html, then the template will say, for instance, "Project not found" instead of just "page not found".

What is the best way to do this?

1 Answer 1

4

The errorhandler route already has an error argument. When you call abort(), Flask throws an HTTPException, which errorhandler is waiting for. The main idea here is that you can create your own exception hierarchy or one exception with different properties and use it in your errorhandler template.

The second idea is to use flashing: on exception, flash a message and abort(), then in your errorhandler template pick up this message.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I "create my own exceptions hierarchy?" Won't HTTPException always be thrown when I call abort()?
See flask.pocoo.org/docs/api/…, you can catch any exception with errorhandler. So your exception can be look like class ProjectNotFoundException(Exception): pass and catch with @app.errorhandler(ProjectNotFoundException).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.