error handling in asynchronous node.js calls

前端 未结 10 1661
感动是毒
感动是毒 2020-12-12 19:32

I\'m new to node.js although I\'m pretty familiar with JavaScript in general. My question is regarding \"best practices\" on how to handle errors in node.js.

Normall

10条回答
  •  既然无缘
    2020-12-12 19:50

    I give an answer to my own question... :)

    As it seems there is no way around to manually catch errors. I now use a helper function that itself returns a function containing a try/catch block. Additionally, my own web server class checks if either the request handling function calls response.end() or the try/catch helper function waitfor() (raising an exception otherwise). This avoids to a great extent that request are mistakenly left unprotected by the developer. It isn't a 100% error-prone solution but works well enough for me.

    handler.waitfor = function(callback) {
      var me=this;
    
      // avoid exception because response.end() won't be called immediately:
      this.waiting=true;
    
      return function() {
        me.waiting=false;
        try {
          callback.apply(this, arguments);
    
          if (!me.waiting && !me.finished)
            throw new Error("Response handler returned and did neither send a "+
              "response nor did it call waitfor()");
    
        } catch (e) {
          me.handleException(e);
        }
      }
    }
    

    This way I just have to add a inline waitfor() call to be on the safe side.

    function handleRequest(request, response, handler) {
      fs.read(fd, buffer, 0, 10, null, handler.waitfor(
        function(error, bytesRead, buffer) {
    
          buffer.unknownFunction();  // causes exception
          response.end(buffer);
        }
      )); //fs.read
    }
    

    The actual checking mechanism is a little more complex, but it should be clear how it works. If someone is interested I can post the full code here.

提交回复
热议问题