explodinglabs / jsonrpcserver

Process incoming JSON-RPC requests in Python
MIT License
186 stars 40 forks source link

Return a response object from methods #134

Closed bcb closed 3 years ago

bcb commented 3 years ago

Currently we're raising an InvalidParamsError or ApiError to return a failure response.

@method
def fruits(color):
    if color not in ("red", "orange", "yellow"):
        raise InvalidParamsError("No fruits of that colour")

I would prefer not to raise an exception for these, because it

  1. uses exceptions to control flow
  2. makes the @method a partial function
  3. goes against the functional style of the rest of the library

Instead we should return an error response.

bcb commented 3 years ago

Since we already have Response classes defined (used internally), we could use those.

from jsonrpcserver.response import InvalidParamsResponse

@method
def fruits(color):
    if color not in ("red", "orange", "yellow"):
        return InvalidParamsResponse("No fruits of that colour")
    return "banana"

And the same for ApiError:

    return ApiErrorResponse("Can't fulfill the request")

Even for success response, I would like to return a Response type:

return SuccessResponse("banana")

This may not be a breaking change, we could leave the existing functionality but also allow returning the Response objects.