Socket onerror callback not honored

Posted on
  • Socket instances don't seem to use the attached 'error' listener on error:

    >s = net.connect({host: 'xxx', port: 1883}, print)
    >s.on('error', (e)=>print('EEE',e))
    >s.end()
    >s
    =Socket: { type: 0, 
      "#onconnect": function () { [native code] }, 
      opt: { 
        host: "neptune", 
        port: 1883 }, 
      conn: false, 
      "#onerror": function (e) { ... }, 
      clsNow: true, cls: true, endd: true }
    
    >s.write('x')
    Uncaught Error: This socket is closed.
     at line 1 col 12
    s.write('x')
               ^
    

    Is this expected behaviour?
    I'm asking because in NodeJS, when an error listener is attached, no exception is thrown but the listener called (with the exception message) instead. If Espruino did the same, the last line should read like this:
    EEE Error: This socket is closed. ... (EEE because the listener prints it, then the error.)

  • That's interesting - that behaviour is expected though.

    The error callback will get called in case of connection errors, but not for an error like that which is caused by a call on the socket.

    While it makes sense to have it behave the same as Node.js, I'd say the current behaviour is actually pretty useful - it really helps to have a stack trace from the offending line of code.

  • Wouldn't the same trace information be in the error callback? The advantage of no exception thrown is that you attach the callback once, while one has to do try/catch in all places now.
    I'm fine though with the current behaviour. Espruino is great and pretty powerful!

  • Wouldn't the same trace information be in the error callback?

    Unfortunately not - you just get a string describing the error as a parameter, but you have no idea where in the program it came from.

    Understood about the try..catch though - it's annoying having to do it.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Socket onerror callback not honored

Posted by Avatar for Steffen @Steffen

Actions