How to use the sanic.exceptions.ServerError function in sanic

To help you get started, we’ve selected a few sanic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yunstanford / jinja2-sanic / tests / test_render.py View on Github external
}
        )
    )

    @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"
github ashleysommer / sanic-cors / tests / decorator / test_exception_interception.py View on Github external
        @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)
github ashleysommer / sanicpluginsframework / tests / test_plugin_exception.py View on Github external
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
github huge-success / sanic / tests / test_exceptions.py View on Github external
def handler_error(request):
        raise ServerError("OK")
github huge-success / sanic / sanic / server.py View on Github external
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:
github gusibi / Metis / apis / auth / validators.py View on Github external
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,
        )
github vltr / sanic-boom / src / sanic_boom / protocol.py View on Github external
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)
github songtao-git / wings-sanic / src / schema / fields.py View on Github external
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__))