From 588b4712bfb71afebe91a34cd1d33c9a52ce16b1 Mon Sep 17 00:00:00 2001 From: Raphael Deem Date: Sat, 20 May 2017 01:21:09 -0700 Subject: [PATCH] add exception decorator --- sanic/exceptions.py | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/sanic/exceptions.py b/sanic/exceptions.py index 989de72d..3a501983 100644 --- a/sanic/exceptions.py +++ b/sanic/exceptions.py @@ -117,6 +117,20 @@ INTERNAL_SERVER_ERROR_HTML = ''' ''' +SANIC_EXCEPTIONS = {} + + +def add_status_code(code): + """ + Decorator used for adding exceptions to SANIC_EXCEPTIONS. + """ + def class_decorator(cls): + cls.status_code = code + SANIC_EXCEPTIONS[code] = cls + return cls + return class_decorator + + class SanicException(Exception): def __init__(self, message, status_code=None): @@ -126,14 +140,17 @@ class SanicException(Exception): self.status_code = status_code +@add_status_code(404) class NotFound(SanicException): status_code = 404 +@add_status_code(400) class InvalidUsage(SanicException): status_code = 400 +@add_status_code(500) class ServerError(SanicException): status_code = 500 @@ -151,10 +168,12 @@ class FileNotFound(NotFound): self.relative_url = relative_url +@add_status_code(408) class RequestTimeout(SanicException): status_code = 408 +@add_status_code(413) class PayloadTooLarge(SanicException): status_code = 413 @@ -163,6 +182,7 @@ class HeaderNotFound(SanicException): status_code = 400 +@add_status_code(416) class ContentRangeError(SanicException): status_code = 416 @@ -178,18 +198,6 @@ class InvalidRangeType(ContentRangeError): pass -# Would be nice to define this at the top but the class is not defined yet -# which is throwing an error. -SANIC_EXCEPTIONS = { - 400: InvalidUsage, - 404: NotFound, - 408: RequestTimeout, - 413: PayloadTooLarge, - 416: ContentRangeError, - 500: ServerError, -} - - def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response