处理事件侦听器(如WebSocket.onmessage)中的意外数据

时间:2016-10-20 12:24:58

标签: javascript javascript-events websocket

如何处理意外事件,例如奇怪的数据,损坏的数据,意外的数据或事件监听器中出现的问题。

WebSocket公开了onmessage事件监听器。如果收到意想不到的东西,该如何处理? 通过抛出异常,登录到控制台,默默地忽略它?

  • 如果事件监听器抛出异常,那么我猜没有什么可以捕获该异常。那不好吗?
  • 在生产中使用console.log是不是很糟糕?
  • 如果事件监听器默默地忽略该消息?那不是很糟糕吗?
let socket = new WebSocket('wss://www.example.com/');
socket.onmessage = function (event) {
    if (event.data === 'GARBAGE') {
        // What is the appropriate thing to do here?
    }
}

1 个答案:

答案 0 :(得分:0)

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.