From 43c5a4bb6074dfbd1920e5cfeea7a85ef295b515 Mon Sep 17 00:00:00 2001 From: Benny Date: Sun, 7 May 2017 00:53:06 +0800 Subject: [PATCH] add exception_base --- sanic/app.py | 19 +++++++++++++++++++ sanic/handlers.py | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/sanic/app.py b/sanic/app.py index 8d846c3e..0e59c9c5 100644 --- a/sanic/app.py +++ b/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. diff --git a/sanic/handlers.py b/sanic/handlers.py index 6a87fd5d..31e21c9a 100644 --- a/sanic/handlers.py +++ b/sanic/handlers.py @@ -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