add exception_base
This commit is contained in:
parent
8d3fd75ec2
commit
43c5a4bb60
19
sanic/app.py
19
sanic/app.py
|
@ -272,6 +272,25 @@ class Sanic:
|
|||
|
||||
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
|
||||
def middleware(self, middleware_or_request):
|
||||
"""Decorate and register middleware to be called before a request.
|
||||
|
|
|
@ -23,6 +23,7 @@ class ErrorHandler:
|
|||
|
||||
def __init__(self):
|
||||
self.handlers = []
|
||||
self.handlers_base = []
|
||||
self.cached_handlers = {}
|
||||
self.debug = False
|
||||
|
||||
|
@ -55,6 +56,9 @@ class ErrorHandler:
|
|||
|
||||
def add(self, exception, handler):
|
||||
self.handlers.append((exception, handler))
|
||||
|
||||
def add_base(self, exception, handler):
|
||||
self.handlers_base.append((exception, handler))
|
||||
|
||||
def lookup(self, exception):
|
||||
handler = self.cached_handlers.get(exception, self._missing)
|
||||
|
@ -63,6 +67,15 @@ class ErrorHandler:
|
|||
if isinstance(exception, exception_class):
|
||||
self.cached_handlers[type(exception)] = 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
|
||||
handler = None
|
||||
return handler
|
||||
|
|
Loading…
Reference in New Issue
Block a user