net: don't throw on net.Server.close()
authorcjihrig <cjihrig@gmail.com>
Fri, 16 May 2014 02:48:27 +0000 (22:48 -0400)
committerFedor Indutny <fedor@indutny.com>
Sun, 18 May 2014 13:59:52 +0000 (17:59 +0400)
When close() is called on a non-listening server, a synchronous
error is thrown. This commit causes the error to be passed to
the asynchronous callback function instead.

Signed-off-by: Fedor Indutny <fedor@indutny.com>
doc/api/net.markdown
lib/net.js
test/simple/test-http-unix-socket.js

index 957b708..a6bf2f6 100644 (file)
@@ -206,7 +206,8 @@ Stops the server from accepting new connections and keeps existing
 connections. This function is asynchronous, the server is finally
 closed when all connections are ended and the server emits a `'close'`
 event. Optionally, you can pass a callback to listen for the `'close'`
-event.
+event. If present, the callback is invoked with any potential error
+as the first and only argument.
 
 ### server.address()
 
index 8cc13bc..3b4f7da 100644 (file)
@@ -1341,16 +1341,20 @@ Server.prototype.close = function(cb) {
     self._emitCloseIfDrained();
   }
 
-  if (!this._handle) {
-    // Throw error. Follows net_legacy behaviour.
-    throw new Error('Not running');
+  if (cb) {
+    if (!this._handle) {
+      this.once('close', function() {
+        cb(new Error('Not running'));
+      });
+    } else {
+      this.once('close', cb);
+    }
   }
 
-  if (cb) {
-    this.once('close', cb);
+  if (this._handle) {
+    this._handle.close();
+    this._handle = null;
   }
-  this._handle.close();
-  this._handle = null;
 
   if (this._usingSlaves) {
     var self = this,
index 01c29c1..66d5403 100644 (file)
@@ -62,7 +62,12 @@ server.listen(common.PIPE, function() {
     res.on('end', function() {
       assert.equal(res.body, 'hello world\n');
       body_ok = true;
-      server.close();
+      server.close(function(error) {
+        assert.equal(error, undefined);
+        server.close(function(error) {
+          assert.equal(error && error.message, 'Not running');
+        });
+      });
     });
   });
 
@@ -79,9 +84,4 @@ process.on('exit', function() {
   assert.ok(status_ok);
   assert.ok(headers_ok);
   assert.ok(body_ok);
-
-  // Double close should throw. Follows net_legacy behaviour.
-  assert.throws(function() {
-    server.close();
-  });
 });