Skip to content
Advertisement

Handle unexpected data in event listeners such as WebSocket.onmessage

How do I handle unexpected things such as weird data, corrupted data, unexpected data, or something going wrong in an event listener.

WebSocket exposes a onmessage event listener. If it were to receive something unexpected, how is this to be dealt with? By throwing an exception, logging to console, silently ignoring it?

  • If the event listener throws an exception, then I guess there is nothing to catch that exception. Is that bad?
  • Use console.log in production is bad?
  • If the event listener silently ignore the message? Isn’t that bad?
let socket = new WebSocket('wss://www.example.com/');
socket.onmessage = function (event) {
    if (event.data === 'GARBAGE') {
        // What is the appropriate thing to do here?
    }
}

Advertisement

Answer

It really depends on your application and how critical the problem is.

  • Generally, putting output to console for production, especially errors, is not such a good thing. End-users might not like seeing “error” or “exception” in the console log, especially, if the application handles some sensitive information.
  • One have to be careful in using console.log, especially, if printing some variables, as you may introduce some memory leaks.

Ignoring an error should be a choice by design. If you are receiving an unexpected data to the listener, it means that your system is not working as intended somewhere. At least, you should know why you are getting such input.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement