3

At times when using Polkadot.JS/Api connections would either timeout or become disconnected from the provider. When this happens the app crashes and exits.

Is there any native setting to reconnect without throwing an error?

1 Answer 1

1

Reconnecting is a default feature of WsProvider:

/**
   * @param {string | string[]}  endpoint    The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
   * @param {number | false} autoConnectMs Whether to connect automatically or not (default). Provided value is used as a delay between retries.
   * @param {Record<string, string>} headers The headers provided to the underlying WebSocket
   * @param {number} [timeout] Custom timeout value used per request . Defaults to `DEFAULT_TIMEOUT_MS`
   */

In all cases the API will handle reconnecting automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to when connection is lost, the API will manage re-connections.

In cases where the API does not support the chain being connected to, such as it using an unknown metadata version, the ready promise will fail to resolve and instead reject.

By error I am assuming you mean something like this in your logs:

2023-06-01 15:17:46          API-WS: disconnected from wss://localhost:9944: 1006:: connection failed
2023-06-01 15:17:46          API-WS: disconnected from wss://localhost:9944: 1006:: connection failed
2023-06-01 15:17:46          API-WS: disconnected from wss://localhost:9944: 1006:: connection failed
2023-06-01 15:17:46          API-WS: disconnected from wss://localhost:9944: 1006:: connection failed
2023-06-01 15:17:46          API-WS: disconnected from wss://localhost:9944: 1006:: connection failed
2023-06-01 15:17:46          API-WS: disconnected from wss://localhost:9944: 1006:: connection failed

You could do something like this:

import { ApiPromise, WsProvider } from '@polkadot/api';

export const reconnect = async () => {
    const provider = new WsProvider('wss://localhost:9944', 1000);

    // Skip logging the default message
    console.error = (message) => {
        if (typeof message === 'string' && message.startsWith('API-WS: disconnected from')) {
            return; // Skip logging the default message
        }
    };

    provider.on('disconnected', () => {
        // Optional custom message
        console.log('WebSocket connection closed unexpectedly.');
    });

    const api = await ApiPromise.create({ provider });
};

The second param in the WsProvider constructor is called "autoConnectMs" and you can set to true - which would try to reconnect immediately with no delay OR you can specify a number which would be the milliseconds to delay before reconnect.

1
  • This really good information, thank you. To be more specific, the error that I'm facing is API-WS: disconnected from wss://xxx.yyy.zz: 1006:: Abnormal Closure Under these circumstances I would like the API to reconnect. Jun 2, 2023 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.