Skip to content
Myr

Merge pull request #1291 from flying-sheep/errorhandler-rework

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixed and intuitivized exception handling

authored by Markus Unterwaditzer · committed by Markus Unterwaditzer · parents 06f2be3, b31252d · Browse files · 2 files+182 added−30 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+182 added−30 removed

  • tests:+113 added−0 removed
  • other:+69 added−30 removed

2 files+182 added−30 removed

modified:flask/app.py+69 added-30 removed
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1111import os12import sys13from threading import Lock14from datetime import timedelta15from itertools import chain16from functools import update_wrapper17from collections import Mapping1819from werkzeug.datastructures import ImmutableDict20from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed, BadRequest22 MethodNotAllowed, BadRequest, default_exceptions2324from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _endpoint_from_view_func, find_package26from . import json, cli
5 unmodified lines
32from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34from .signals import request_started, request_finished, got_request_exception, \35 request_tearing_down, appcontext_tearing_down36from ._compat import reraise, string_types, text_type, integer_types36from ._compat import reraise, string_types, text_type, integer_types, iterkeys3738# a lock used for logger initialization39_logger_lock = Lock()40
1036 unmodified lines
1077 self.view_functions[endpoint] = f1078 return f1079 return decorator10801081 @staticmethod1082 def _get_exc_class_and_code(exc_class_or_code):1083 """Ensure that we register only exceptions as handler keys"""1084 if isinstance(exc_class_or_code, integer_types):1085 exc_class = default_exceptions[exc_class_or_code]1086 else:1087 exc_class = exc_class_or_code1088 1089 assert issubclass(exc_class, Exception)1090 1091 if issubclass(exc_class, HTTPException):1092 return exc_class, exc_class.code1093 else:1094 return exc_class, None1095 1096 @setupmethod1097 def errorhandler(self, code_or_exception):1098 """A decorator that is used to register a function give a given1099 error code. Example::
50 unmodified lines
1150 self._register_error_handler(None, code_or_exception, f)11511152 @setupmethod1153 def _register_error_handler(self, key, code_or_exception, f):1139 if isinstance(code_or_exception, HTTPException):1140 code_or_exception = code_or_exception.code1141 if isinstance(code_or_exception, integer_types):1142 assert code_or_exception != 500 or key is None, \1143 'It is currently not possible to register a 500 internal ' \1144 'server error on a per-blueprint level.'1145 self.error_handler_spec.setdefault(key, {})[code_or_exception] = f1146 else:1147 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \1148 .append((code_or_exception, f))1154 """1155 :type key: None|str1156 :type code_or_exception: int|T<=Exception1157 :type f: callable1158 """1159 if isinstance(code_or_exception, HTTPException): # old broken behavior1160 raise ValueError(1161 'Tried to register a handler for an exception instance {0!r}. '1162 'Handlers can only be registered for exception classes or HTTP error codes.'1163 .format(code_or_exception))1164 1165 exc_class, code = self._get_exc_class_and_code(code_or_exception)1166 1167 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1168 handlers[exc_class] = f11691170 @setupmethod1171 def template_filter(self, name=None):1172 """A decorator that is used to register custom template filter.
232 unmodified lines
1405 """1406 self.url_default_functions.setdefault(None, []).append(f)1407 return f14081409 def _find_error_handler(self, e):1410 """Finds a registered error handler for the request’s blueprint.1411 If neither blueprint nor App has a suitable handler registered, returns None1412 """1413 exc_class, code = self._get_exc_class_and_code(type(e))1414 1415 def find_superclass(handler_map):1416 if not handler_map:1417 return None1418 for superclass in exc_class.__mro__:1419 if superclass is BaseException:1420 return None1421 handler = handler_map.get(superclass)1422 if handler is not None:1423 handler_map[exc_class] = handler # cache for next time exc_class is raised1424 return handler1425 return None1426 1427 # try blueprint handlers1428 handler = find_superclass(self.error_handler_spec.get(request.blueprint, {}).get(code))1429 1430 if handler is not None:1431 return handler1432 1433 # fall back to app handlers1434 return find_superclass(self.error_handler_spec[None].get(code))14351436 def handle_http_exception(self, e):1437 """Handles an HTTP exception. By default this will invoke the1438 registered error handlers and fall back to returning the1439 exception as response.14401441 .. versionadded:: 0.31442 """1396 handlers = self.error_handler_spec.get(request.blueprint)1443 # Proxy exceptions don't have error codes. We want to always return1444 # those unchanged as errors1445 if e.code is None:1446 return e1401 if handlers and e.code in handlers:1402 handler = handlers[e.code]1403 else:1404 handler = self.error_handler_spec[None].get(e.code)1447 1448 handler = self._find_error_handler(e)1449 if handler is None:1450 return e1451 return handler(e)1452
33 unmodified lines
1486 # ensure not to trash sys.exc_info() at that point in case someone1487 # wants the traceback preserved in handle_http_exception. Of course1488 # we cannot prevent users from trashing it themselves in a custom1489 # trap_http_exception method so that's their fault then.14461447 blueprint_handlers = ()1448 handlers = self.error_handler_spec.get(request.blueprint)1449 if handlers is not None:1450 blueprint_handlers = handlers.get(None, ())1451 app_handlers = self.error_handler_spec[None].get(None, ())1452 for typecheck, handler in chain(blueprint_handlers, app_handlers):1453 if isinstance(e, typecheck):1454 return handler(e)14551490 1491 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1492 return self.handle_http_exception(e)14931494 handler = self._find_error_handler(e)1495 1496 if handler is None:1459 reraise(exc_type, exc_value, tb)1497 reraise(exc_type, exc_value, tb)1498 return handler(e)14991500 def handle_exception(self, e):1501 """Default exception handling that kicks in when an exception1502 occurs that is not caught. In debug mode the exception will
5 unmodified lines
1508 """1509 exc_type, exc_value, tb = sys.exc_info()15101511 got_request_exception.send(self, exception=e)1473 handler = self.error_handler_spec[None].get(500)1512 handler = self._find_error_handler(InternalServerError())15131514 if self.propagate_exceptions:1515 # if we want to repropagate the exception, we can attempt to1516 # raise it with the whole traceback in case we can do that
449 unmodified lines
added:tests/test_user_error_handler.py+113 added
1# -*- coding: utf-8 -*-2from werkzeug.exceptions import Forbidden, InternalServerError3import flask456def test_error_handler_subclass():7 app = flask.Flask(__name__)89 class ParentException(Exception):10 pass1112 class ChildExceptionUnregistered(ParentException):13 pass1415 class ChildExceptionRegistered(ParentException):16 pass1718 @app.errorhandler(ParentException)19 def parent_exception_handler(e):20 assert isinstance(e, ParentException)21 return 'parent'2223 @app.errorhandler(ChildExceptionRegistered)24 def child_exception_handler(e):25 assert isinstance(e, ChildExceptionRegistered)26 return 'child-registered'2728 @app.route('/parent')29 def parent_test():30 raise ParentException()3132 @app.route('/child-unregistered')33 def unregistered_test():34 raise ChildExceptionUnregistered()3536 @app.route('/child-registered')37 def registered_test():38 raise ChildExceptionRegistered()394041 c = app.test_client()4243 assert c.get('/parent').data == b'parent'44 assert c.get('/child-unregistered').data == b'parent'45 assert c.get('/child-registered').data == b'child-registered'464748def test_error_handler_http_subclass():49 app = flask.Flask(__name__)5051 class ForbiddenSubclassRegistered(Forbidden):52 pass5354 class ForbiddenSubclassUnregistered(Forbidden):55 pass5657 @app.errorhandler(403)58 def code_exception_handler(e):59 assert isinstance(e, Forbidden)60 return 'forbidden'6162 @app.errorhandler(ForbiddenSubclassRegistered)63 def subclass_exception_handler(e):64 assert isinstance(e, ForbiddenSubclassRegistered)65 return 'forbidden-registered'6667 @app.route('/forbidden')68 def forbidden_test():69 raise Forbidden()7071 @app.route('/forbidden-registered')72 def registered_test():73 raise ForbiddenSubclassRegistered()7475 @app.route('/forbidden-unregistered')76 def unregistered_test():77 raise ForbiddenSubclassUnregistered()787980 c = app.test_client()8182 assert c.get('/forbidden').data == b'forbidden'83 assert c.get('/forbidden-unregistered').data == b'forbidden'84 assert c.get('/forbidden-registered').data == b'forbidden-registered'858687def test_error_handler_blueprint():88 bp = flask.Blueprint('bp', __name__)89 90 @bp.errorhandler(500)91 def bp_exception_handler(e):92 return 'bp-error'93 94 @bp.route('/error')95 def bp_test():96 raise InternalServerError()97 98 app = flask.Flask(__name__)99 100 @app.errorhandler(500)101 def app_exception_handler(e):102 return 'app-error'103 104 @app.route('/error')105 def app_test():106 raise InternalServerError()107 108 app.register_blueprint(bp, url_prefix='/bp')109 110 c = app.test_client()111 112 assert c.get('/error').data == b'app-error'113 assert c.get('/bp/error').data == b'bp-error'