2021-10-02 23:02:56 +01:00
|
|
|
from inspect import signature
|
2021-09-29 21:53:49 +01:00
|
|
|
from typing import Dict, List, Optional, Tuple, Type
|
2021-08-31 10:32:51 +01:00
|
|
|
|
2021-09-29 21:53:49 +01:00
|
|
|
from sanic.errorpages import BaseRenderer, HTMLRenderer, exception_response
|
2017-02-16 02:54:00 +00:00
|
|
|
from sanic.exceptions import (
|
2018-10-18 05:20:16 +01:00
|
|
|
ContentRangeError,
|
|
|
|
HeaderNotFound,
|
|
|
|
InvalidRangeType,
|
2018-10-14 01:55:33 +01:00
|
|
|
)
|
2021-04-10 19:35:53 +01:00
|
|
|
from sanic.log import error_logger
|
2021-09-29 21:53:49 +01:00
|
|
|
from sanic.models.handler_types import RouteHandler
|
2021-03-07 12:54:45 +00:00
|
|
|
from sanic.response import text
|
2017-01-31 01:04:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ErrorHandler:
|
2018-12-08 06:27:10 +00:00
|
|
|
"""
|
|
|
|
Provide :class:`sanic.app.Sanic` application with a mechanism to handle
|
|
|
|
and process any and all uncaught exceptions in a way the application
|
|
|
|
developer will set fit.
|
|
|
|
|
|
|
|
This error handling framework is built into the core that can be extended
|
|
|
|
by the developers to perform a wide range of tasks from recording the error
|
2018-12-08 07:11:42 +00:00
|
|
|
stats to reporting them to an external service that can be used for
|
|
|
|
realtime alerting system.
|
2018-12-08 06:27:10 +00:00
|
|
|
|
|
|
|
"""
|
2018-12-08 07:11:42 +00:00
|
|
|
|
2021-09-29 21:53:49 +01:00
|
|
|
# Beginning in v22.3, the base renderer will be TextRenderer
|
2021-10-02 23:02:56 +01:00
|
|
|
def __init__(
|
|
|
|
self, fallback: str = "auto", base: Type[BaseRenderer] = HTMLRenderer
|
|
|
|
):
|
2021-09-29 21:53:49 +01:00
|
|
|
self.handlers: List[Tuple[Type[BaseException], RouteHandler]] = []
|
|
|
|
self.cached_handlers: Dict[
|
|
|
|
Tuple[Type[BaseException], Optional[str]], Optional[RouteHandler]
|
|
|
|
] = {}
|
2017-01-31 01:04:51 +00:00
|
|
|
self.debug = False
|
2021-09-29 21:53:49 +01:00
|
|
|
self.fallback = fallback
|
|
|
|
self.base = base
|
2017-01-31 01:04:51 +00:00
|
|
|
|
2021-10-02 23:02:56 +01:00
|
|
|
@classmethod
|
|
|
|
def finalize(cls, error_handler):
|
|
|
|
if not isinstance(error_handler, cls):
|
|
|
|
error_logger.warning(
|
|
|
|
f"Error handler is non-conforming: {type(error_handler)}"
|
|
|
|
)
|
|
|
|
|
|
|
|
sig = signature(error_handler.lookup)
|
|
|
|
if len(sig.parameters) == 1:
|
|
|
|
error_logger.warning(
|
|
|
|
DeprecationWarning(
|
|
|
|
"You are using a deprecated error handler. The lookup "
|
|
|
|
"method should accept two positional parameters: "
|
|
|
|
"(exception, route_name: Optional[str]). "
|
|
|
|
"Until you upgrade your ErrorHandler.lookup, Blueprint "
|
|
|
|
"specific exceptions will not work properly. Beginning "
|
|
|
|
"in v22.3, the legacy style lookup method will not "
|
|
|
|
"work at all."
|
|
|
|
),
|
|
|
|
)
|
|
|
|
error_handler._lookup = error_handler._legacy_lookup
|
|
|
|
|
|
|
|
def _full_lookup(self, exception, route_name: Optional[str] = None):
|
|
|
|
return self.lookup(exception, route_name)
|
|
|
|
|
|
|
|
def _legacy_lookup(self, exception, route_name: Optional[str] = None):
|
|
|
|
return self.lookup(exception)
|
|
|
|
|
2021-08-31 10:32:51 +01:00
|
|
|
def add(self, exception, handler, route_names: Optional[List[str]] = None):
|
2018-12-08 06:27:10 +00:00
|
|
|
"""
|
|
|
|
Add a new exception handler to an already existing handler object.
|
|
|
|
|
|
|
|
:param exception: Type of exception that need to be handled
|
|
|
|
:param handler: Reference to the method that will handle the exception
|
|
|
|
|
2018-12-08 07:11:42 +00:00
|
|
|
:type exception: :class:`sanic.exceptions.SanicException` or
|
|
|
|
:class:`Exception`
|
2018-12-08 06:27:10 +00:00
|
|
|
:type handler: ``function``
|
|
|
|
|
|
|
|
:return: None
|
|
|
|
"""
|
2021-08-31 10:32:51 +01:00
|
|
|
# self.handlers is deprecated and will be removed in version 22.3
|
2017-03-06 14:00:04 +00:00
|
|
|
self.handlers.append((exception, handler))
|
|
|
|
|
2021-08-31 10:32:51 +01:00
|
|
|
if route_names:
|
|
|
|
for route in route_names:
|
|
|
|
self.cached_handlers[(exception, route)] = handler
|
|
|
|
else:
|
|
|
|
self.cached_handlers[(exception, None)] = handler
|
|
|
|
|
2021-10-02 23:02:56 +01:00
|
|
|
def lookup(self, exception, route_name: Optional[str] = None):
|
2018-12-08 06:27:10 +00:00
|
|
|
"""
|
|
|
|
Lookup the existing instance of :class:`ErrorHandler` and fetch the
|
|
|
|
registered handler for a specific type of exception.
|
|
|
|
|
|
|
|
This method leverages a dict lookup to speedup the retrieval process.
|
|
|
|
|
|
|
|
:param exception: Type of exception
|
|
|
|
|
2018-12-08 07:11:42 +00:00
|
|
|
:type exception: :class:`sanic.exceptions.SanicException` or
|
|
|
|
:class:`Exception`
|
2018-12-08 06:27:10 +00:00
|
|
|
|
|
|
|
:return: Registered function if found ``None`` otherwise
|
|
|
|
"""
|
2021-06-21 12:14:07 +01:00
|
|
|
exception_class = type(exception)
|
|
|
|
|
2021-08-31 10:32:51 +01:00
|
|
|
for name in (route_name, None):
|
|
|
|
exception_key = (exception_class, name)
|
|
|
|
handler = self.cached_handlers.get(exception_key)
|
|
|
|
if handler:
|
2021-06-21 12:14:07 +01:00
|
|
|
return handler
|
2021-08-31 10:32:51 +01:00
|
|
|
|
|
|
|
for name in (route_name, None):
|
|
|
|
for ancestor in type.mro(exception_class):
|
|
|
|
exception_key = (ancestor, name)
|
|
|
|
if exception_key in self.cached_handlers:
|
|
|
|
handler = self.cached_handlers[exception_key]
|
|
|
|
self.cached_handlers[
|
|
|
|
(exception_class, route_name)
|
|
|
|
] = handler
|
|
|
|
return handler
|
|
|
|
|
|
|
|
if ancestor is BaseException:
|
|
|
|
break
|
|
|
|
self.cached_handlers[(exception_class, route_name)] = None
|
2021-06-21 12:14:07 +01:00
|
|
|
handler = None
|
2017-03-06 14:00:04 +00:00
|
|
|
return handler
|
2017-01-31 01:04:51 +00:00
|
|
|
|
2021-10-02 23:02:56 +01:00
|
|
|
_lookup = _full_lookup
|
|
|
|
|
2017-01-31 01:04:51 +00:00
|
|
|
def response(self, request, exception):
|
2017-02-14 19:10:19 +00:00
|
|
|
"""Fetches and executes an exception handler and returns a response
|
|
|
|
object
|
2017-01-31 01:04:51 +00:00
|
|
|
|
2018-12-08 06:27:10 +00:00
|
|
|
:param request: Instance of :class:`sanic.request.Request`
|
2017-01-31 01:04:51 +00:00
|
|
|
:param exception: Exception to handle
|
2018-12-08 06:27:10 +00:00
|
|
|
|
|
|
|
:type request: :class:`sanic.request.Request`
|
2018-12-08 07:11:42 +00:00
|
|
|
:type exception: :class:`sanic.exceptions.SanicException` or
|
|
|
|
:class:`Exception`
|
2018-12-08 06:27:10 +00:00
|
|
|
|
|
|
|
:return: Wrap the return value obtained from :func:`default`
|
|
|
|
or registered handler for that type of exception.
|
2017-01-31 01:04:51 +00:00
|
|
|
"""
|
2021-08-31 10:32:51 +01:00
|
|
|
route_name = request.name if request else None
|
2021-10-02 23:02:56 +01:00
|
|
|
handler = self._lookup(exception, route_name)
|
2017-03-06 14:00:04 +00:00
|
|
|
response = None
|
2017-01-31 01:04:51 +00:00
|
|
|
try:
|
2017-03-06 14:00:04 +00:00
|
|
|
if handler:
|
2018-10-05 15:33:46 +01:00
|
|
|
response = handler(request, exception)
|
2017-03-06 14:00:04 +00:00
|
|
|
if response is None:
|
2018-02-20 23:50:27 +00:00
|
|
|
response = self.default(request, exception)
|
2017-01-31 01:04:51 +00:00
|
|
|
except Exception:
|
2018-09-29 21:20:20 +01:00
|
|
|
try:
|
|
|
|
url = repr(request.url)
|
|
|
|
except AttributeError:
|
|
|
|
url = "unknown"
|
2018-10-14 01:55:33 +01:00
|
|
|
response_message = (
|
|
|
|
"Exception raised in exception handler " '"%s" for uri: %s'
|
|
|
|
)
|
2021-04-10 19:35:53 +01:00
|
|
|
error_logger.exception(response_message, handler.__name__, url)
|
2018-09-29 21:20:20 +01:00
|
|
|
|
2017-01-31 01:04:51 +00:00
|
|
|
if self.debug:
|
2018-09-29 21:20:20 +01:00
|
|
|
return text(response_message % (handler.__name__, url), 500)
|
2017-01-31 01:04:51 +00:00
|
|
|
else:
|
2018-10-14 01:55:33 +01:00
|
|
|
return text("An error occurred while handling an error", 500)
|
2017-01-31 01:04:51 +00:00
|
|
|
return response
|
|
|
|
|
|
|
|
def default(self, request, exception):
|
2018-12-08 06:27:10 +00:00
|
|
|
"""
|
|
|
|
Provide a default behavior for the objects of :class:`ErrorHandler`.
|
|
|
|
If a developer chooses to extent the :class:`ErrorHandler` they can
|
|
|
|
provide a custom implementation for this method to behave in a way
|
|
|
|
they see fit.
|
|
|
|
|
|
|
|
:param request: Incoming request
|
|
|
|
:param exception: Exception object
|
|
|
|
|
|
|
|
:type request: :class:`sanic.request.Request`
|
2018-12-08 07:11:42 +00:00
|
|
|
:type exception: :class:`sanic.exceptions.SanicException` or
|
|
|
|
:class:`Exception`
|
2018-12-08 06:27:10 +00:00
|
|
|
:return:
|
|
|
|
"""
|
2021-08-07 21:24:48 +01:00
|
|
|
self.log(request, exception)
|
2021-09-29 21:53:49 +01:00
|
|
|
return exception_response(
|
|
|
|
request,
|
|
|
|
exception,
|
|
|
|
debug=self.debug,
|
|
|
|
base=self.base,
|
|
|
|
fallback=self.fallback,
|
|
|
|
)
|
2021-08-07 21:24:48 +01:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def log(request, exception):
|
2020-01-20 14:58:14 +00:00
|
|
|
quiet = getattr(exception, "quiet", False)
|
|
|
|
if quiet is False:
|
|
|
|
try:
|
|
|
|
url = repr(request.url)
|
|
|
|
except AttributeError:
|
|
|
|
url = "unknown"
|
|
|
|
|
2021-04-10 19:35:53 +01:00
|
|
|
error_logger.exception(
|
|
|
|
"Exception occurred while handling uri: %s", url
|
|
|
|
)
|
2017-01-31 01:04:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ContentRangeHandler:
|
2018-12-08 06:27:10 +00:00
|
|
|
"""
|
|
|
|
A mechanism to parse and process the incoming request headers to
|
|
|
|
extract the content range information.
|
|
|
|
|
|
|
|
:param request: Incoming api request
|
|
|
|
:param stats: Stats related to the content
|
|
|
|
|
|
|
|
:type request: :class:`sanic.request.Request`
|
|
|
|
:type stats: :class:`posix.stat_result`
|
|
|
|
|
|
|
|
:ivar start: Content Range start
|
|
|
|
:ivar end: Content Range end
|
|
|
|
:ivar size: Length of the content
|
|
|
|
:ivar total: Total size identified by the :class:`posix.stat_result`
|
|
|
|
instance
|
|
|
|
:ivar ContentRangeHandler.headers: Content range header ``dict``
|
|
|
|
"""
|
2018-10-14 01:55:33 +01:00
|
|
|
|
|
|
|
__slots__ = ("start", "end", "size", "total", "headers")
|
2017-01-31 01:04:51 +00:00
|
|
|
|
|
|
|
def __init__(self, request, stats):
|
|
|
|
self.total = stats.st_size
|
2021-04-08 11:30:12 +01:00
|
|
|
_range = request.headers.getone("range", None)
|
2017-01-31 01:04:51 +00:00
|
|
|
if _range is None:
|
2018-10-14 01:55:33 +01:00
|
|
|
raise HeaderNotFound("Range Header Not Found")
|
|
|
|
unit, _, value = tuple(map(str.strip, _range.partition("=")))
|
|
|
|
if unit != "bytes":
|
2017-01-31 01:04:51 +00:00
|
|
|
raise InvalidRangeType(
|
2018-10-14 01:55:33 +01:00
|
|
|
"%s is not a valid Range Type" % (unit,), self
|
|
|
|
)
|
|
|
|
start_b, _, end_b = tuple(map(str.strip, value.partition("-")))
|
2017-01-31 01:04:51 +00:00
|
|
|
try:
|
|
|
|
self.start = int(start_b) if start_b else None
|
|
|
|
except ValueError:
|
|
|
|
raise ContentRangeError(
|
2018-10-14 01:55:33 +01:00
|
|
|
"'%s' is invalid for Content Range" % (start_b,), self
|
|
|
|
)
|
2017-01-31 01:04:51 +00:00
|
|
|
try:
|
|
|
|
self.end = int(end_b) if end_b else None
|
|
|
|
except ValueError:
|
|
|
|
raise ContentRangeError(
|
2018-10-14 01:55:33 +01:00
|
|
|
"'%s' is invalid for Content Range" % (end_b,), self
|
|
|
|
)
|
2017-01-31 01:04:51 +00:00
|
|
|
if self.end is None:
|
|
|
|
if self.start is None:
|
|
|
|
raise ContentRangeError(
|
2018-10-14 01:55:33 +01:00
|
|
|
"Invalid for Content Range parameters", self
|
|
|
|
)
|
2017-01-31 01:04:51 +00:00
|
|
|
else:
|
|
|
|
# this case represents `Content-Range: bytes 5-`
|
2018-11-07 13:36:56 +00:00
|
|
|
self.end = self.total - 1
|
2017-01-31 01:04:51 +00:00
|
|
|
else:
|
|
|
|
if self.start is None:
|
|
|
|
# this case represents `Content-Range: bytes -5`
|
|
|
|
self.start = self.total - self.end
|
2018-11-07 13:36:56 +00:00
|
|
|
self.end = self.total - 1
|
2017-01-31 01:04:51 +00:00
|
|
|
if self.start >= self.end:
|
|
|
|
raise ContentRangeError(
|
2018-10-14 01:55:33 +01:00
|
|
|
"Invalid for Content Range parameters", self
|
|
|
|
)
|
2018-11-07 13:36:56 +00:00
|
|
|
self.size = self.end - self.start + 1
|
2017-01-31 01:04:51 +00:00
|
|
|
self.headers = {
|
2018-10-14 01:55:33 +01:00
|
|
|
"Content-Range": "bytes %s-%s/%s"
|
|
|
|
% (self.start, self.end, self.total)
|
|
|
|
}
|
2017-01-31 01:04:51 +00:00
|
|
|
|
|
|
|
def __bool__(self):
|
|
|
|
return self.size > 0
|