Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Add ApiError
* Allows methods to signal user-defined error condition.
  • Loading branch information
st31ny committed Nov 13, 2019
commit 8ad206878f5e22a73c0132a77f4e36ba6c67f811
23 changes: 23 additions & 0 deletions doc/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,29 @@ The dispatcher will give the appropriate response:
*To include the "No fruits of that colour" message in the response, pass
debug=True to dispatch.*

## Errors

To send a custom error response to the client, raise an `ApiError`.

```python
@method
def get_page(path):
if path.startswith('private/'):
raise ApiError("This path is forbidden", code=403, data={'path': 'private/'})
```

The dispatcher sends an appropriate error response:

```python
>>> response = dispatch('{"jsonrpc": "2.0", "method": "get_page", "params": ["private/index.html"], "id": 1}')
>>> str(response)
'{"jsonrpc": "2.0", "error": {"code": 403, "message": "This path is forbidden", "data": {"path": "private/"}}, "id": 1}'
```

Both the error code and data are optional and may be omitted. The `data` parameter
accepts any serializable value while `code` must be an integer. Some negative error codes
are, however, reserved by the jsonrpc standard.

## Async

Asyncio is supported, allowing requests to be dispatched to coroutines.
Expand Down
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
26 changes: 26 additions & 0 deletions jsonrpcserver/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Exceptions"""
from typing import Any

from .response import UNSPECIFIED

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

def __init__(
self,
message: str,
code: int = 1,
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'] == 1
assert 'data' not in error_dict

# call_requests

Expand Down