2016-10-03 05:11:38 +01:00
|
|
|
from .response import text
|
|
|
|
from traceback import format_exc
|
2016-10-03 04:47:15 +01:00
|
|
|
|
2016-10-15 03:53:49 +01:00
|
|
|
|
2016-10-03 05:11:38 +01:00
|
|
|
class SanicException(Exception):
|
2016-10-15 03:53:49 +01:00
|
|
|
def __init__(self, message, status_code=None):
|
|
|
|
super().__init__(message)
|
|
|
|
if status_code is not None:
|
|
|
|
self.status_code = status_code
|
|
|
|
|
2016-10-03 05:11:38 +01:00
|
|
|
|
|
|
|
class NotFound(SanicException):
|
2016-10-15 03:53:49 +01:00
|
|
|
status_code = 404
|
|
|
|
|
|
|
|
|
2016-10-03 05:11:38 +01:00
|
|
|
class InvalidUsage(SanicException):
|
2016-10-15 03:53:49 +01:00
|
|
|
status_code = 400
|
|
|
|
|
|
|
|
|
2016-10-03 05:11:38 +01:00
|
|
|
class ServerError(SanicException):
|
2016-10-15 03:53:49 +01:00
|
|
|
status_code = 500
|
|
|
|
|
2016-10-03 04:47:15 +01:00
|
|
|
|
2016-10-24 09:21:06 +01:00
|
|
|
class FileNotFound(NotFound):
|
|
|
|
status_code = 404
|
|
|
|
|
|
|
|
def __init__(self, message, path, relative_url):
|
|
|
|
super().__init__(message)
|
|
|
|
self.path = path
|
|
|
|
self.relative_url = relative_url
|
|
|
|
|
|
|
|
|
2016-11-26 04:55:45 +00:00
|
|
|
class RequestTimeout(SanicException):
|
|
|
|
status_code = 408
|
|
|
|
|
|
|
|
|
2016-12-04 01:50:32 +00:00
|
|
|
class PayloadTooLarge(SanicException):
|
|
|
|
status_code = 413
|
|
|
|
|
|
|
|
|
2016-10-03 04:47:15 +01:00
|
|
|
class Handler:
|
2016-10-15 03:53:49 +01:00
|
|
|
handlers = None
|
|
|
|
|
|
|
|
def __init__(self, sanic):
|
|
|
|
self.handlers = {}
|
|
|
|
self.sanic = sanic
|
|
|
|
|
|
|
|
def add(self, exception, handler):
|
|
|
|
self.handlers[exception] = handler
|
|
|
|
|
|
|
|
def response(self, request, exception):
|
|
|
|
"""
|
2016-10-16 02:28:24 +01:00
|
|
|
Fetches and executes an exception handler and returns a response object
|
2016-10-15 03:53:49 +01:00
|
|
|
:param request: Request
|
|
|
|
:param exception: Exception to handle
|
|
|
|
:return: Response object
|
|
|
|
"""
|
|
|
|
handler = self.handlers.get(type(exception), self.default)
|
|
|
|
response = handler(request=request, exception=exception)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def default(self, request, exception):
|
|
|
|
if issubclass(type(exception), SanicException):
|
2016-10-16 14:01:59 +01:00
|
|
|
return text(
|
|
|
|
"Error: {}".format(exception),
|
|
|
|
status=getattr(exception, 'status_code', 500))
|
2016-10-15 03:53:49 +01:00
|
|
|
elif self.sanic.debug:
|
2016-10-16 14:01:59 +01:00
|
|
|
return text(
|
|
|
|
"Error: {}\nException: {}".format(
|
|
|
|
exception, format_exc()), status=500)
|
2016-10-15 03:53:49 +01:00
|
|
|
else:
|
2016-10-16 14:01:59 +01:00
|
|
|
return text(
|
|
|
|
"An error occurred while generating the request", status=500)
|