mandrewcito / signalrcore

SignalR Core python client
https://mandrewcito.github.io/signalrcore/
MIT License
115 stars 53 forks source link

hcshmk/invocation_id - Read invocation_id from method parameters, letting user override it if desired. #65

Closed ghost closed 2 years ago

ghost commented 3 years ago

This merge request lets the user supply their own invocation_id to the BaseHubConnection.send method. The purpose is to allow the user to easily perform error handling on individual requests/calls/invocations by registering an on_error event handler that can take advantage of this, as demonstrated below:

# Dict pairing uuid with a function
error_handlers: Dict[UUID, Callable[[str], None]] = dict()

# Handle server-sent exceptions by looking up uuid for that particular call/invocation
def on_error(self, completion_message: CompletionMessage):
    uuid = UUID(completion_message.invocation_id)
    error = completion_message.error
    handler = error_handlers[uuid]
    del error_handlers[uuid]
    handler(error)
connection.on_error(on_error)

# Call hub function with simple error handling
single_use_uuid = uuid.uuid4()
error_handlers[uuid] = lambda error_msg: print(f'This specific call to DoStuff failed with message: {error_msg}')
connection.send(method = 'DoStuff',
                arguments = [],
                on_invocation = lambda response: on_success(response.result),
                invocation_id=str(single_use_uuid))

Demo code is kept brief and simple, just for proof of concept. With a few extra lines and a wrapper function, you can get the send function to raise an exception in python whenever invoke fails serverside.

ghost commented 3 years ago

Mentioning @sillydan1