Fixed and intuitivized exception handling
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Phil Schaf · committed by Phil Schaf · parent dac45f6 · Browse files · 1 file·+98 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+98 added−26 removed
- other:+98 added−26 removed
Provenance
- Commit
eae48d9- Tree
7dffb5e- Author
Phil Schaf <flying-sheep@web.de>- Committer
Phil Schaf <flying-sheep@web.de>- Parent
dac45f6
1 file changed+98 added−26 removed
modified:flask/app.py+98 added-26 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+from collections import ChainMap12 13 import os14 import sys15 from threading import Lock3 unmodified lines19 20 from werkzeug.datastructures import ImmutableDict21 from werkzeug.routing import Map, Rule, RequestRedirect, BuildError22 from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed, BadRequest23+ MethodNotAllowed, BadRequest, default_exceptions24 25 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \26 locked_cached_property, _endpoint_from_view_func, find_package27 from . import json, cli37 unmodified lines65 return f(self, *args, **kwargs)66 return update_wrapper(wrapper_func, f)67 68 69+def get_http_code(error_class_or_instance):70+ if (71+ isinstance(error_class_or_instance, HTTPException) or72+ isinstance(error_class_or_instance, type) and73+ issubclass(error_class_or_instance, HTTPException)74+ ):75+ return error_class_or_instance.code76+ return None77+78+79+class ExceptionHandlerDict(ChainMap):80+ """A dict storing exception handlers or falling back to the default ones81+ 82+ Designed to be app.error_handler_spec[blueprint_or_none]83+ And hold a Exception → handler function mapping.84+ Converts error codes to default HTTPException subclasses.85+ 86+ Returns None if no handler is defined for blueprint or app87+ """88+ def __init__(self, app, blueprint):89+ self.app = app90+ init = super(ExceptionHandlerDict, self).__init__91+ if blueprint: # fall back to app mapping92+ init({}, app.error_handler_spec[None])93+ else:94+ init({})95+ 96+ def get_class(self, exc_class_or_code):97+ if isinstance(exc_class_or_code, integer_types):98+ # ensure that we register only exceptions as keys99+ exc_class = default_exceptions[exc_class_or_code]100+ else:101+ assert issubclass(exc_class_or_code, Exception)102+ exc_class = exc_class_or_code103+ return exc_class104+ 105+ def __contains__(self, e_or_c):106+ return super(ExceptionHandlerDict, self).__contains__(self.get_class(e_or_c))107+ 108+ def __getitem__(self, e_or_c):109+ return super(ExceptionHandlerDict, self).__getitem__(self.get_class(e_or_c))110+ 111+ def __setitem__(self, e_or_c, handler):112+ assert callable(handler)113+ return super(ExceptionHandlerDict, self).__setitem__(self.get_class(e_or_c), handler)114+ 115+ def find_handler(self, ex_instance):116+ assert isinstance(ex_instance, Exception)117+ 118+ for superclass in type(ex_instance).mro():119+ if superclass is BaseException:120+ return None121+ handler = self.get(superclass)122+ if handler is not None:123+ return handler124+ return None125+126+127 class Flask(_PackageBoundObject):128 """The flask object implements a WSGI application and acts as the central129 object. It is passed the name of the module or package of the130 application. Once it is created it will act as a central registry for292 unmodified lines423 self.view_functions = {}424 425 # support for the now deprecated `error_handlers` attribute. The426 # :attr:`error_handler_spec` shall be used now.368- self._error_handlers = {}427+ self._error_handlers = ExceptionHandlerDict(self, None)428 429 #: A dictionary of all registered error handlers. The key is ``None``430 #: for error handlers active on the application, otherwise the key is431 #: the name of the blueprint. Each key points to another dictionary762 unmodified lines1194 self._register_error_handler(None, code_or_exception, f)1195 1196 @setupmethod1197 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, \1198+ """1199+ :type key: None|str1200+ :type code_or_exception: int|T<=Exception1201+ :type f: callable1202+ """1203+ assert not isinstance(code_or_exception, HTTPException) # old broken behavior1204+ 1205+ code = code_or_exception1206+ is_code = isinstance(code_or_exception, integer_types)1207+ if not is_code:1208+ if issubclass(code_or_exception, HTTPException):1209+ code = code_or_exception.code1210+ else:1211+ code = None1212+ 1213+ handlers = self.error_handler_spec.setdefault(key, ExceptionHandlerDict(self, key))1214+ 1215+ if is_code:1216+ # TODO: why is this?1217+ assert code != 500 or key is None, \1218 'It is currently not possible to register a 500 internal ' \1219 '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))1220+ 1221+ handlers[code_or_exception] = f1222 1223 @setupmethod1224 def template_filter(self, name=None):1225 """A decorator that is used to register custom template filter.232 unmodified lines1458 """1459 self.url_default_functions.setdefault(None, []).append(f)1460 return f1461 1462+ def _find_error_handler(self, e):1463+ """Finds a registered error handler for the request’s blueprint.1464+ If nether blueprint nor App has a suitable handler registered, returns None1465+ """1466+ handlers = self.error_handler_spec.get(request.blueprint, self.error_handler_spec[None])1467+ return handlers.find_handler(e)1468+1469 def handle_http_exception(self, e):1470 """Handles an HTTP exception. By default this will invoke the1471 registered error handlers and fall back to returning the1472 exception as response.1473 1474 .. versionadded:: 0.31475 """1396- handlers = self.error_handler_spec.get(request.blueprint)1476 # Proxy exceptions don't have error codes. We want to always return1477 # those unchanged as errors1478 if e.code is None:1479 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)1480+ 1481+ handler = self._find_error_handler(e)1482 if handler is None:1483 return e1484 return handler(e)1485 33 unmodified lines1519 # ensure not to trash sys.exc_info() at that point in case someone1520 # wants the traceback preserved in handle_http_exception. Of course1521 # we cannot prevent users from trashing it themselves in a custom1522 # trap_http_exception method so that's their fault then.1446-1447- 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)1455-1523+ 1524 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1525 return self.handle_http_exception(e)1526 1527+ handler = self._find_error_handler(e)1528+ 1529+ if handler is None:1459- reraise(exc_type, exc_value, tb)1530+ reraise(exc_type, exc_value, tb)1531+ return handler(e)1532 1533 def handle_exception(self, e):1534 """Default exception handling that kicks in when an exception1535 occurs that is not caught. In debug mode the exception will463 unmodified lines