11

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.

6

Use

web3.isConnected() 

it returns 'true' if connected, and 'false' when doesn't

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

  • 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? – Zeeshan Ahmad Khalil Sep 9 at 7:43
18

If you use web3js.1.0.0-beta.23. This version 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'));
  • 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.