Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch socket.io errors and prevent them from showing up in the console?

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?

like image 434
michael Avatar asked Feb 01 '13 15:02

michael


3 Answers

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))
like image 105
leonheess Avatar answered Oct 10 '22 09:10

leonheess


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.

like image 45
josh3736 Avatar answered Oct 10 '22 10:10

josh3736


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

like image 34
Brmm Avatar answered Oct 10 '22 09:10

Brmm