Repository navigation
Replies: 1 comment
|
In ethers v6, subscription error handling is split across two layers: the provider-level error event and the individual listener. 1. Provider-level error handlerCatch errors from all subscriptions globally: provider.on('error', (error) => {
console.error('Provider error:', error);
// Reconnect logic, alerting, etc.
});This fires when the underlying transport (WebSocket, polling) encounters an error — not when your event listener callback throws. 2. Wrap individual event listeners in try/catchIf your callback throws, it does NOT propagate to the provider error handler. You must catch it yourself: const filter = {
address: contractAddress,
topics: [ethers.id('Transfer(address,address,uint256)')],
};
provider.on(filter, async (log) => {
try {
const parsed = contract.interface.parseLog(log);
await processTransfer(parsed);
} catch (err) {
console.error('Error processing event:', err);
// Don't let a single bad event kill the listener
}
});3. Handling WebSocket disconnectsWebSocket subscriptions can silently die. Use a heartbeat pattern: import { WebSocketProvider } from 'ethers';
function createResilientProvider(url: string) {
let provider = new WebSocketProvider(url);
let pingInterval: NodeJS.Timeout;
function setupHealthCheck() {
pingInterval = setInterval(async () => {
try {
await provider.getBlockNumber();
} catch {
console.log('WebSocket dead, reconnecting...');
clearInterval(pingInterval);
provider.destroy();
provider = new WebSocketProvider(url);
setupListeners(provider);
setupHealthCheck();
}
}, 30_000);
}
setupHealthCheck();
return provider;
}4. Cleanup subscriptionsAlways remove listeners when done to prevent memory leaks: const handler = (log: Log) => { /* ... */ };
// Subscribe
provider.on(filter, handler);
// Unsubscribe
provider.off(filter, handler);
// Or remove all listeners for a filter
provider.removeAllListeners(filter);5. Polling vs WebSocket error surfaces
The general pattern is: |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I added error decoding for the error that I have been facing recently: #5034. Since it doesn't find any decoding, it just fallbacked to the
@TODOconsole.log that polluted my logs on everytick/poll. And there is no way I can find to catch the error and unsubscribe so it stops polling.Any suggestions?
All reactions