I'm running socket.io on node.js and the socket.io client on an Apache website. If I don't start the node.js server and load the client page, the error event is triggered with an empty error message, which results in the following console output:
GET http://example.com:1337/socket.io/1/?t=1359731838906 socket.io.js:1659
Socket.handshake socket.io.js:1659
Socket.connect socket.io.js:1699
Socket socket.io.js:1551
io.connect socket.io.js:94
(anonymous function) general.js:7
(anonymous function)
What can I do to stop this error being written to the console?
You can not "catch" these errors in the sense that they are not appearing in the console but you can still act upon them by listening for 'connect_error'
, 'connect_failed'
and 'disconnect'
of the socket and then either handling them directly or redirecting them to a custom function like handleErrors()
:
const socket = io.connect(url, { reconnection: false })
socket.on('update', data => console.log(data))
socket.on('connect_error', err => handleErrors(err))
socket.on('connect_failed', err => handleErrors(err))
socket.on('disconnect', err => handleErrors(err))
The only way to hide that error is by never calling io.connect
in the first place – which of course would mean your app's socket functions wouldn't work even if the server is up.
It's important to understand that the error message you're seeing is neither something placed there by socket.io itself (via console.error()
) nor is it an uncaught JS Exception.
The error message is placed in your console by the browser's XHR object itself. It's telling you that a XHR request has failed (since your server isn't running). The stack trace is telling you what code initiated the XHR request; it isn't a trace of an actual Exception.
Since socket.io must make a request to the server, there's no way it (or you) could prevent that error message from appearing in the console if the server isn't responding.
try
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
Not tested this. Found it here Node.js socket.io-client connect_failed / connect_error event
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With