17

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.

hohoho
  • 293
  • 1
  • 2
  • 10

2 Answers2

28

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));
Klesun
  • 218
  • 2
  • 10
Andrey Patseiko
  • 381
  • 1
  • 2
  • 4
  • 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 https://ethereum.stackexchange.com/questions/61612/how-to-catch-connection-issues-to-web3-provider-using-web3-js – Nyxynyx Nov 02 '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 09 '18 at 20:17
11

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

Bharat Mallapur
  • 234
  • 1
  • 7
Viktor
  • 550
  • 4
  • 15
  • 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 09 '19 at 07:43
  • 2
    This is not working for now. Uncaught TypeError: window.web3.isConnected is not a function at :1:13 – Anupam Feb 11 '21 at 09:58