Azure / azure-webpubsub

Azure Web PubSub Service helps you to manage WebSocket connections and do publish and subscribe in an easy way
https://azure.github.io/azure-webpubsub/
MIT License
135 stars 85 forks source link

Documentation on handling `SendMessageError` #806

Open michaeltnguyen opened 1 month ago

michaeltnguyen commented 1 month ago

Give us your feedback about our samples

Which sample do you want to give feedback?

https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/azure-web-pubsub/reference-client-sdk-javascript.md#4-send-messages-to-a-group

The sample is not what you want?

In production, we have occasionally run into the following error:

Type: SendMessageError Message: The connection is not connected. File: Stack: SendMessageError: The connection is not connected. at aVn._sendMessageWithAckId @ at async aVn._sendToGroupAttempt @ at async aVn._operationExecuteWithRetry @ at async aVn.sendToGroup

What is the proper way to handle this error?

Should we be checking the connection status before calling sendAsync? In other words, track status via client.on('connected') and client.on('disconnected'). And in that case, while the status is "disconnected", we would need to store all attempted messages so they can be resent once the client has successfully connected? Or does this library do all of that for us already?

zackliu commented 2 days ago

We suggest handle failure like this: https://learn.microsoft.com/en-us/azure/azure-web-pubsub/reference-client-sdk-javascript#retry

try {
  await client.joinGroup(groupName);
} catch (err) {
  let id = null;
  if (err instanceof SendMessageError) {
    id = err.ackId;
  }
  await client.joinGroup(groupName, {ackId: id});
}

Actually, it has some built-in retries and you can change the retry policy in WebPubSubClientOptions.messageRetryOptions. This gives you flexibility according to your business logic.