Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
}
)
)
@app.route("/")
@jinja2_sanic.template("templates.jinja3")
def func(request):
return {
"Player": "CR7",
"Category": "Soccer",
}
request = mock.Mock()
request.app = app
with pytest.raises(ServerError) as ctx:
await func(request)
assert str(ctx.value) == "Template 'templates.jinja3' not found"
def test_acl_abort_500(request):
raise ServerError("")
def exception(request):
raise ServerError("yep")
@self.app.exception(ServerError, NotFound, Exception)
# Note, async error handlers don't work in Sanic yet.
# async def catch_all_handler(request, exception):
def catch_all_handler(request, exception):
'''
This error handler catches 404s and 500s and returns
status 200 no matter what. It is not a good handler.
'''
return text(return_string, 200)
try:
ModuleNotFoundError
except:
class ModuleNotFoundError(ImportError):
pass
handler = ErrorHandler()
handler.add(ImportError, import_error_handler)
handler.add(CustomError, custom_error_handler)
handler.add(ServerError, server_error_handler)
assert handler.lookup(ImportError()) == import_error_handler
assert handler.lookup(ModuleNotFoundError()) == import_error_handler
assert handler.lookup(CustomError()) == custom_error_handler
assert handler.lookup(ServerError('Error')) == server_error_handler
assert handler.lookup(CustomServerError('Error')) == server_error_handler
# once again to ensure there is no caching bug
assert handler.lookup(ImportError()) == import_error_handler
assert handler.lookup(ModuleNotFoundError()) == import_error_handler
assert handler.lookup(CustomError()) == custom_error_handler
assert handler.lookup(ServerError('Error')) == server_error_handler
assert handler.lookup(CustomServerError('Error')) == server_error_handler
def handler_error(request):
raise ServerError("OK")
try:
keep_alive = self.keep_alive
response.protocol = self
await response.stream(
self.request.version, keep_alive, self.keep_alive_timeout
)
self.log_response(response)
except AttributeError:
logger.error(
"Invalid response object for url %s, "
"Expected Type: HTTPResponse, Actual Type: %s",
self.url,
type(response),
)
self.write_error(ServerError("Invalid response type"))
except RuntimeError:
if self._debug:
logger.error(
"Connection lost before response written @ %s",
self.request.ip,
)
keep_alive = False
except Exception as e:
self.bail_out(
"Writing response failed, connection closed {}".format(repr(e))
)
finally:
if not keep_alive:
self.transport.close()
self.transport = None
else:
status = list(filter.keys())[0]
else:
status = filter.keys()[0]
schemas = filter.get(status)
if not schemas:
# return resp, status, headers
raise ServerError('`%d` is not a defined status code.' % status, 500)
resp, errors = normalize(schemas['schema'], resp)
if schemas['headers']:
headers, header_errors = normalize(
{'properties': schemas['headers']}, headers)
errors.extend(header_errors)
if errors:
raise ServerError('Expectation Failed', 500)
return response.json(
resp,
status=status,
headers=headers,
)
def bail_out(self, message, from_error=False):
if from_error or self.transport.is_closing():
logger.error(
"Transport closed @ %s and exception "
"experienced during error handling",
self.transport.get_extra_info("peername"),
)
logger.debug("Exception:\n%s", traceback.format_exc())
else:
exception = ServerError(message)
self.write_error(exception)
logger.error(message)
def pre_setattr(self, value):
if isinstance(value, self.model_spec):
return value
if isinstance(value, dict):
return self.model_spec(value)
raise exceptions.ServerError('{0}的值设置失败, 应是{1}或者字典类型'.format(self.label, self.model_spec.__name__))