Python Flask error handlers

Writing general error handlers for Python Flask applications is very straightdorward

@app.errorhandler(sqlite3.OperationalError)
def sqlite3_op_error(err):
 return render_template('errors/500.html', errmsg=('Database error: %s' % err))
@app.errorhandler(OperationalError)
def peewee_op_error(err):
 return render_template('errors/500.html', errmsg=('ORM error: %s' % err))
@app.errorhandler(NameError)
def name_error(err):
 return render_template('errors/500.html', errmsg=('Application error: %s' % err))
@app.errorhandler(404)
def page_not_found(err):
 return render_template('errors/404.html', errmsg=(err))
@app.errorhandler(DoesNotExist)
def query_does_not_exist(err):
 return render_template('errors/409.html', errmsg=('Query error: %s' % err))
@app.errorhandler(IntegrityError)
def query_integrity_error(err):
 return render_template('errors/409.html', errmsg=('Integrify error: %s' % err))

A template might take the form

{%- extends "error_layout.html" -%}
{%- block fourzeronine -%}
{{ super() }}

<p>
A database query error has occurred: {{ errmsg }}
</p>
<p>Back to <a href="/">index</a>.
{%- endblock -%}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s