Skip to content

Latest commit

 

History

History
99 lines (70 loc) · 2.78 KB

exceptions.rst

File metadata and controls

99 lines (70 loc) · 2.78 KB

Exception reference

tinyrpc.exc

Adding custom exceptions

Note

As per the specification you should use error codes -32000 to -32099 when adding server specific error messages. Error codes outside the range -32768 to -32000 are available for application specific error codes.

To add custom errors you need to combine an :pyException subclass with the :pyFixedErrorMessageMixin class to create your exception object which you can raise.

So a version of the reverse string example that dislikes palindromes could look like:

from tinyrpc.protocols.jsonrpc import FixedErrorMessageMixin, JSONRPCProtocol
from tinyrpc.dispatch import RPCDispatcher

dispatcher = RPCDispatcher()

class PalindromeError(FixedErrorMessageMixin, Exception):
    jsonrpc_error_code = 99
    message = "Ah, that's cheating!"


@dispatcher.public
def reverse_string(s):
    r = s[::-1]
    if r == s:
        raise PalindromeError()
    return r

Error with data

The specification states that the error element of a reply may contain an optional data property. This property is now available for your use.

There are two ways that you can use to pass additional data with an :pyException. It depends whether your application generates regular exceptions or exceptions derived from :pyFixedErrorMessageMixin.

When using ordinary exceptions you normally pass a single parameter (an error message) to the :pyException constructor. By passing two parameters, the second parameter is assumed to be the data element.

@public
def fn():
    raise Exception('error message', {'msg': 'structured data', 'lst': [1, 2, 3]})

This will produce the reply message:

{   "jsonrpc": "2.0",
    "id": <some id>,
    "error": {
        "code": -32000,
        "message": "error message",
        "data": {"msg": "structured data", "lst": [1, 2, 3]}
    }
}

When using :pyFixedErrorMessageMixin based exceptions the data is passed using a keyword parameter.

class MyException(FixedErrorMessageMixin, Exception):
    jsonrcp_error_code = 99
    message = 'standard message'

@public
def fn():
    raise MyException(data={'msg': 'structured data', 'lst': [1, 2, 3]})

This will produce the reply message:

{   "jsonrpc": "2.0",
    "id": <some id>,
    "error": {
        "code": 99,
        "message": "standard message",
        "data": {"msg": "structured data", "lst": [1, 2, 3]}
    }
}