Browse Source

Register errorhandlers for Exceptions

Allow a default errorhandler by registering
an errorhandler for HTTPException

tests included
pull/2314/head
Florian Sachs 8 years ago committed by cerickson
parent
commit
668061a5fc
  1. 11
      flask/app.py
  2. 25
      tests/test_user_error_handler.py

11
flask/app.py

@ -1484,7 +1484,16 @@ class Flask(_PackageBoundObject):
return handler
# fall back to app handlers
return find_handler(self.error_handler_spec[None].get(code))
handler = find_handler(self.error_handler_spec[None].get(code))
if handler is not None:
return handler
try:
handler = find_handler(self.error_handler_spec[None][None])
except KeyError:
handler = None
return handler
def handle_http_exception(self, e):
"""Handles an HTTP exception. By default this will invoke the

25
tests/test_user_error_handler.py

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from werkzeug.exceptions import Forbidden, InternalServerError
from werkzeug.exceptions import Forbidden, InternalServerError, HTTPException, NotFound
import flask
@ -32,6 +32,29 @@ def test_error_handler_no_match():
assert c.get('/keyerror').data == b'KeyError'
def test_default_error_handler():
app = flask.Flask(__name__)
@app.errorhandler(HTTPException)
def catchall_errorhandler(e):
assert isinstance(e, HTTPException)
assert isinstance(e, NotFound)
return 'default'
@app.errorhandler(Forbidden)
def catchall_errorhandler(e):
assert isinstance(e, Forbidden)
return 'forbidden'
@app.route('/forbidden')
def forbidden():
raise Forbidden()
c = app.test_client()
assert c.get('/undefined').data == b'default'
assert c.get('/forbidden').data == b'forbidden'
def test_error_handler_subclass():
app = flask.Flask(__name__)

Loading…
Cancel
Save