How to use the jsonrpcserver.response.ErrorResponse function in jsonrpcserver

To help you get started, we’ve selected a few jsonrpcserver 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 bcb / jsonrpcserver / tests / test_dispatcher.py View on Github external
def test_examples_invalid_json():
    response = dispatch_pure(
        '[{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method"]',
        Methods(ping),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
        serialize=default_serialize,
        deserialize=default_deserialize,
    )
    assert isinstance(response, ErrorResponse)
    assert (
        str(response)
        == '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Invalid JSON", "data": "Expecting \':\' delimiter: line 1 column 96 (char 95)"}, "id": null}'
    )
github bcb / jsonrpcserver / tests / test_dispatcher.py View on Github external
def test_safe_call_api_error():
    def error():
        raise ApiError("Client Error", code=123, data={"data": 42})

    response = safe_call(
        Request(method="error", id=1),
        Methods(error),
        debug=True,
        serialize=default_serialize,
    )
    assert isinstance(response, ErrorResponse)
    error_dict = response.deserialized()["error"]
    assert error_dict["message"] == "Client Error"
    assert error_dict["code"] == 123
    assert error_dict["data"] == {"data": 42}
github bcb / jsonrpcserver / tests / test_response.py View on Github external
def test_error_response_no_id():
    # Responding with an error to a Notification - this is OK; we do respond to
    # notifications under certain circumstances, such as "invalid json" and "invalid
    # json-rpc".
    assert (
        str(ErrorResponse("foo", id=None, code=-1, debug=True, http_status=200))
        == '{"jsonrpc": "2.0", "error": {"code": -1, "message": "foo"}, "id": null}'
    )
github bcb / jsonrpcserver / tests / test_response.py View on Github external
def test_error_response():
    response = ErrorResponse("foo", id=1, code=-1, debug=True, http_status=200)
    assert response.code == -1
    assert response.message == "foo"
    assert response.wanted == True
    assert (
        str(response)
        == '{"jsonrpc": "2.0", "error": {"code": -1, "message": "foo"}, "id": 1}'
    )
github bcb / jsonrpcserver / tests / test_request.py View on Github external
def test_config_notification_errors_on(self):
        # Should return "method not found" error
        request = Request({"jsonrpc": "2.0", "method": "baz"}, notification_errors=True)
        req = request.call([foo])
        self.assertIsInstance(req, ErrorResponse)
github bcb / jsonrpcserver / jsonrpcserver / response.py View on Github external
self.message = message
        self.data = data
        self.debug = debug

    def deserialized(self) -> dict:
        dct = {
            "jsonrpc": "2.0",
            "error": {"code": self.code, "message": self.message},
            "id": self.id,
        }  # type: Dict[str, Any]
        if self.data is not UNSPECIFIED and self.debug:
            dct["error"]["data"] = self.data
        return dct


class InvalidJSONResponse(ErrorResponse):
    def __init__(
        self, *args: Any, http_status: int = status.HTTP_BAD_REQUEST, **kwargs: Any
    ) -> None:
        super().__init__(
            "Invalid JSON",
            code=status.JSONRPC_PARSE_ERROR_CODE,
            http_status=http_status,
            # Must include an id in error responses, but it's impossible to retrieve
            id=None,
            *args,
            **kwargs,
        )
        assert self.id is None


class InvalidJSONRPCResponse(ErrorResponse):
github bcb / jsonrpcserver / jsonrpcserver / response.py View on Github external
*args: Any,
        http_status: int = status.HTTP_INTERNAL_ERROR,
        **kwargs: Any,
    ) -> None:
        super().__init__(
            "Server error",
            code=status.JSONRPC_SERVER_ERROR_CODE,
            data=f"{exc.__class__.__name__}: {str(exc)}",
            http_status=http_status,
            *args,
            **kwargs,
        )
        self.exc = exc


class ApiErrorResponse(ErrorResponse):
    def __init__(
        self, *args: Any, http_status: int = status.HTTP_BAD_REQUEST, **kwargs: Any
    ) -> None:
        super().__init__(http_status=http_status, *args, **kwargs)


class BatchResponse(Response):
    """
    Returned from batch requests.

    A collection of Responses, either success or error.
    """

    def __init__(
        self,
        responses: Iterable[Response],
github bcb / jsonrpcserver / jsonrpcserver / response.py View on Github external
def __init__(
        self, *args: Any, http_status: int = status.HTTP_BAD_REQUEST, **kwargs: Any
    ) -> None:
        super().__init__(
            "Invalid JSON-RPC",
            code=status.JSONRPC_INVALID_REQUEST_CODE,
            http_status=http_status,
            # Must include an id in error responses, but it's impossible to retrieve
            id=None,
            *args,
            **kwargs,
        )
        assert self.id is None


class MethodNotFoundResponse(ErrorResponse):
    def __init__(
        self, *args: Any, http_status: int = status.HTTP_NOT_FOUND, **kwargs: Any
    ) -> None:
        super().__init__(
            "Method not found",
            code=status.JSONRPC_METHOD_NOT_FOUND_CODE,
            http_status=http_status,
            *args,
            **kwargs,
        )


class InvalidParamsResponse(ErrorResponse):
    def __init__(
        self, *args: Any, http_status: int = status.HTTP_BAD_REQUEST, **kwargs: Any
    ) -> None:
github 21dotco / two1-python / two1 / wallet / socket_rpc_server.py View on Github external
try:
                    if self.server._request_cb is not None:
                        self.server._request_cb(self.data)
                    if self.server._client_lock.acquire(True, 10):
                        lock_acquired = True
                        logger.debug("Dispatching %s" % (self.data))
                        response = dispatcher.dispatch(self.server._methods,
                                                       self.data)
                        logger.debug("Responding with: %s" % response.json_debug)
                    else:
                        # Send a time out response
                        r = Request(self.data)
                        logger.debug("Timed out waiting for lock with request = %s" %
                                     (self.data))
                        request_id = r.request_id if hasattr(r, 'request_id') else None
                        response = ErrorResponse(http_status=HTTP_STATUS_CODES[408],
                                                 request_id=request_id,
                                                 code=-32000,  # Server error
                                                 message="Timed out waiting for lock")
                except Exception as e:
                    if logger is not None:
                        logger.exception(e)
                finally:
                    if lock_acquired:
                        self.server._client_lock.release()

                try:
                    json_str = json.dumps(response.json_debug) + "\n"
                    msg = json_str.encode()
                    logger.debug("Message length = %d" % len(msg))
                    self.request.sendall(msg)
                except BrokenPipeError:
github bcb / jsonrpcserver / jsonrpcserver / response.py View on Github external
class MethodNotFoundResponse(ErrorResponse):
    def __init__(
        self, *args: Any, http_status: int = status.HTTP_NOT_FOUND, **kwargs: Any
    ) -> None:
        super().__init__(
            "Method not found",
            code=status.JSONRPC_METHOD_NOT_FOUND_CODE,
            http_status=http_status,
            *args,
            **kwargs,
        )


class InvalidParamsResponse(ErrorResponse):
    def __init__(
        self, *args: Any, http_status: int = status.HTTP_BAD_REQUEST, **kwargs: Any
    ) -> None:
        super().__init__(
            "Invalid parameters",
            code=status.JSONRPC_INVALID_PARAMS_CODE,
            http_status=http_status,
            *args,
            **kwargs,
        )


class ExceptionResponse(ErrorResponse):
    """Sent for unhandled exceptions - 'server error'."""

    def __init__(