Refactor promise handling in Communicator class#97
Conversation
- Removed unnecessary async from the promise constructor in _Call_function. - Improved error handling in sendData calls by using Promise.resolve and catch. - Added try-catch block around sendData in the return handling to prevent unhandled promise rejections.
There was a problem hiding this comment.
Pull request overview
This PR refactors promise handling in the Communicator class to prevent unhandled promise rejections that occur when WebSocket connections close unexpectedly during data transmission. The fix addresses two critical methods where errors from sendData() were not properly caught, leading to application crashes in production environments.
Key Changes:
- Removed the async Promise executor anti-pattern from
_Call_functionmethod - Added proper error handling and promise cleanup when
sendData()fails in_Call_function - Added try-catch wrapper around
sendData()calls in_Send_returnmethod to handle closed connections
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| await this.sendData(props.return); | ||
| try { | ||
| await this.sendData(props.return); | ||
| } catch {} |
There was a problem hiding this comment.
The empty catch block silently swallows all errors from sendData(). While this might be intentional for handling closed connections, it makes debugging difficult and hides unexpected errors. Consider at minimum logging the error at debug/trace level, or checking the error type to only swallow expected connection-closed errors. This would help developers troubleshoot issues where sendData() fails for unexpected reasons (e.g., serialization errors, network issues).
| } catch {} | |
| } catch (error) { | |
| console.debug("Failed to send data in _Send_return:", error); | |
| } |
Fix: Prevent unhandled promise rejections in Communicator methods
Problem
Two methods in
Communicatorclass had error handling issues:_Call_function: Used an anti-patternnew Promise(async (resolve, reject) => { await this.sendData(...) })_Send_return: Missing error handling forawait this.sendData(...)callsThis causes unhandled promise rejections when:
sendData()throws an error (e.g., connection state is CLOSED)Impact
unhandledRejectionhandlers as workaroundExample Error
Solution
1. Fixed
_Call_functionmethodReplaced the async Promise executor pattern with explicit error handling:
Before:
After:
2. Fixed
_Send_returnmethodAdded error handling for
sendData()calls when sending return values:Before:
After:
Benefits
sendData()are caught and handledTesting
Related Issues
This fix addresses the common issue where applications using TGrid need to implement global
unhandledRejectionhandlers to prevent crashes when connections close unexpectedly.