Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add ApiError
* Allows methods to signal user-defined error condition.
  • Loading branch information
st31ny committed Oct 27, 2019
commit 8572f1491f7de5577c6d37afed4f2554e4e1f4f1
1 change: 1 addition & 0 deletions jsonrpcserver/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
from .dispatcher import dispatch
from .methods import add as method
from .server import serve
from .errors import ApiError
11 changes: 11 additions & 0 deletions jsonrpcserver/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from .request import NOCONTEXT, Request
from .response import (
BatchResponse,
ErrorResponse,
ExceptionResponse,
InvalidJSONResponse,
InvalidJSONRPCResponse,
Expand All @@ -33,6 +34,9 @@
Response,
SuccessResponse,
)
from .errors import (
ApiError,
)

request_logger = logging.getLogger(__name__ + ".request")
response_logger = logging.getLogger(__name__ + ".response")
Expand Down Expand Up @@ -132,6 +136,13 @@ def handle_exceptions(request: Request, debug: bool) -> Generator:
handler.response = InvalidParamsResponse(
id=request.id, data=str(exc), debug=debug
)
except ApiError as exc: # Method signals custom error
handler.response = ErrorResponse(
str(exc), code=exc.code, data=exc.data,
id=request.id,
# always set debug to send data to client
debug=True,
)
except Exception as exc: # Other error inside method - server error
handler.response = ExceptionResponse(exc, id=request.id, debug=debug)
finally:
Expand Down
27 changes: 27 additions & 0 deletions jsonrpcserver/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Exceptions"""
from typing import Any

from .response import UNSPECIFIED
from . import status

class ApiError(RuntimeError):
""" A method responds with a custom error """

def __init__(
self,
message: str,
code: int = status.JSONRPC_SERVER_ERROR_CODE,
data: Any = UNSPECIFIED,
):
"""
Args:
message: A string providing a short description of the error, eg. "Invalid
params".
code: A Number that indicates the error type that occurred. This MUST be an
integer.
data: A Primitive or Structured value that contains additional information
about the error. This may be omitted.
"""
super().__init__(message)
self.code = code
self.data = data
27 changes: 27 additions & 0 deletions tests/test_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
NotificationResponse,
SuccessResponse,
)
from jsonrpcserver.errors import ApiError


def ping():
Expand Down Expand Up @@ -81,6 +82,32 @@ def test_safe_call_invalid_args():
)
assert isinstance(response, InvalidParamsResponse)

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=False
)
assert isinstance(response, ErrorResponse)
response_dict = response.deserialized()
error_dict = response_dict['error']
assert error_dict['message'] == "Client Error"
assert error_dict['code'] == 123
assert error_dict['data'] == {'data': 42}

def test_safe_call_api_error_minimal():
def error():
raise ApiError("Client Error")
response = safe_call(
Request(method="error", id=1), Methods(error), debug=False
)
assert isinstance(response, ErrorResponse)
response_dict = response.deserialized()
error_dict = response_dict['error']
assert error_dict['message'] == "Client Error"
assert error_dict['code'] == -32000
assert 'data' not in error_dict

# call_requests

Expand Down