13

I am connecting to local node from browser like:

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

If there is no node running at localhost, I see an error in browser console:

Error: Invalid JSON RPC response: ""

Is there a way to catch this error and provide useful informations to the user? I have tried adding callbacks to new Web3() and new HttpProvider() calls, but none of them is firing.

7

If you are using any web3 version 0.20.x or earlier, then you can use

web3.isConnected() 

it returns 'true' if connected, and 'false' when it isn't connected.

NOTE: If you are using web3 v1.0.0-beta.x or higher, then look at the below answer posted by Andrey Patseiko.

if(!web3.isConnected()) {

    // show some dialog to ask the user to start a node

} else {

   // start web3 filters, calls, etc

}

see https://github.com/ethereum/wiki/wiki/JavaScript-API#web3isconnected

3
  • Just starting to work with Web3js, but in my case isConnected() is always returning true, regardless in my local nodes are running or not. Any ways around this to validate network connectivity? Thanks!
    – danboh
    Apr 28 '18 at 15:53
  • Can we check that it is connected to which RPC also? Sep 9 '19 at 7:43
  • This is not working for now. Uncaught TypeError: window.web3.isConnected is not a function at <anonymous>:1:13 Feb 11 at 9:58
23

If you use web3js.1.0.0-beta.23 or later versions, these versions don't have method isConnected().

Instead you can use method web.eth.net.isListening() web3 documentation, or check any network parameter, for example get id network. Example:

 const web = new Web3();
 web.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8545'));      
 web.eth.net.isListening()
   .then(() => console.log('is connected'))
   .catch(e => console.log('Wow. Something went wrong: '+ e));
3
  • You can also do the same thing inside a function (async) with let netIsListening = await web3.eth.net.isListening(); and try{}catch(e){}
    – Andy B.
    Mar 13 '18 at 15:30
  • @AndyB. Tried your approach but the program gets stuck at the await statement if theres no node accepting connections at that address. Posted details at ethereum.stackexchange.com/questions/61612/…
    – Nyxynyx
    Nov 2 '18 at 17:30
  • Well in that case could you wrap it up in a try function? Of course you will need to wrap everything up in a big async function. async ()=>{ try{ let netIsListening = await web3.eth.net.isListening(); }catch(e){ console.error(e); } }
    – Andy B.
    Nov 9 '18 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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