add exception_base

This commit is contained in:
Benny 2017-05-07 00:53:06 +08:00
parent 8d3fd75ec2
commit 43c5a4bb60
2 changed files with 32 additions and 0 deletions

View File

@ -272,6 +272,25 @@ class Sanic:
return response return response
# Decorator
def exception_base(self, *exceptions):
"""Decorate a function to be registered as a handler for exceptions
:param exceptions: exceptions
:return: decorated function
"""
def response(handler):
for exception in exceptions:
if isinstance(exception, (tuple, list)):
for e in exception:
self.error_handler.add_base(e, handler)
else:
self.error_handler.add_base(exception, handler)
return handler
return response
# Decorator # Decorator
def middleware(self, middleware_or_request): def middleware(self, middleware_or_request):
"""Decorate and register middleware to be called before a request. """Decorate and register middleware to be called before a request.

View File

@ -23,6 +23,7 @@ class ErrorHandler:
def __init__(self): def __init__(self):
self.handlers = [] self.handlers = []
self.handlers_base = []
self.cached_handlers = {} self.cached_handlers = {}
self.debug = False self.debug = False
@ -56,6 +57,9 @@ class ErrorHandler:
def add(self, exception, handler): def add(self, exception, handler):
self.handlers.append((exception, handler)) self.handlers.append((exception, handler))
def add_base(self, exception, handler):
self.handlers_base.append((exception, handler))
def lookup(self, exception): def lookup(self, exception):
handler = self.cached_handlers.get(exception, self._missing) handler = self.cached_handlers.get(exception, self._missing)
if handler is self._missing: if handler is self._missing:
@ -63,6 +67,15 @@ class ErrorHandler:
if isinstance(exception, exception_class): if isinstance(exception, exception_class):
self.cached_handlers[type(exception)] = handler self.cached_handlers[type(exception)] = handler
return handler return handler
for exception_class, handler in self.handlers_base:
try:
raise
except exception_class:
return handler
except Exception:
pass
self.cached_handlers[type(exception)] = None self.cached_handlers[type(exception)] = None
handler = None handler = None
return handler return handler