Add #379 again and make related test rework

Original PR: https://github.com/channelcat/sanic/pull/379
This commit is contained in:
Jeong YunWon
2017-03-06 23:00:04 +09:00
parent 875790e862
commit 429e90183b
2 changed files with 65 additions and 5 deletions

View File

@@ -16,9 +16,12 @@ from sanic.response import text, html
class ErrorHandler:
handlers = None
cached_handlers = None
_missing = object()
def __init__(self):
self.handlers = {}
self.handlers = []
self.cached_handlers = {}
self.debug = False
def _render_traceback_html(self, exception, request):
@@ -37,7 +40,18 @@ class ErrorHandler:
path=request.path)
def add(self, exception, handler):
self.handlers[exception] = handler
self.handlers.append((exception, handler))
def lookup(self, exception):
handler = self.cached_handlers.get(exception, self._missing)
if handler is self._missing:
for exception_class, handler in self.handlers:
if isinstance(exception, exception_class):
self.cached_handlers[type(exception)] = handler
return handler
self.cached_handlers[type(exception)] = None
handler = None
return handler
def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
@@ -47,9 +61,13 @@ class ErrorHandler:
:param exception: Exception to handle
:return: Response object
"""
handler = self.handlers.get(type(exception), self.default)
handler = self.lookup(exception)
response = None
try:
response = handler(request=request, exception=exception)
if handler:
response = handler(request=request, exception=exception)
if response is None:
response = self.default(request=request, exception=exception)
except Exception:
self.log(format_exc())
if self.debug: