Reputation: 4483
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?
Upvotes: 13
Views: 35603
Reputation: 21351
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))
Upvotes: 20
Reputation: 31
If you're using Socket.io v4 and need to capture middleware errors, try
// client-side
socket.on("connect_error", (err) => {
console.log(err.message); // prints the message associated with the error
});
source https://socket.io/docs/v4/middlewares/#handling-middleware-error
Upvotes: 1
Reputation: 144872
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.
Upvotes: 13
Reputation: 340
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
Upvotes: 1