Node.js未被捕获的套接字异常 - 套接字已关闭

时间:2012-10-04 20:23:45

标签: sockets node.js promise

这是问题所在。写入一个封闭的套接字时我得到一个异常,并且异常没有被try catch捕获,大概是因为它在promise中。

promise.then(function (val) {
  try {
    sock.write(val + tcpDelimiter);
  } catch (err) {
    logger.info('yeah right this will not work at all');
  }
})
.fail(function (error) {});

此外,将process.uncaughtexception添加到主应用程序也无济于事。

这是控制台输出:

 2012-10-04T19:22:21.109Z - error: uncaughtException date=Thu Oct 04
 2012 19:22:21 GMT+0000 (UTC), pid=21508, uid=0, gid=0,
 cwd=/home/ec2-user/js-proxy, execPath=/usr/bin/nodejs,
 version=v0.6.18, argv=[/usr/local/bin/node,
 /home/ec2-user/js-proxy/app.js, --jsproxy], rss=13914112,
 heapTotal=5634752, heapUsed=4082564, loadavg=[0.0380859375,
 0.08056640625, 0.060546875], uptime=1721344.103162099, trace=[column=19, file=net.js, function=Socket._write, line=474,
 method=_write, native=false, column=15, file=net.js,
 function=Socket.write, line=466, method=write, native=false,
 column=24, file=/home/ec2-user/js-proxy/app.js, function=null,
 line=408, method=null, native=false, column=32,
 file=/home/ec2-user/js-proxy/node_modules/q/q.js, function=_fulfilled,
 line=860, method=null, native=false, column=34,
 file=/home/ec2-user/js-proxy/node_modules/q/q.js, function=null,
 line=881, method=null, native=false, column=9,
 file=/home/ec2-user/js-proxy/node_modules/q/q.js,
 function=makePromise.promiseSend, line=553, method=promiseSend,
 native=false, column=28,
 file=/home/ec2-user/js-proxy/node_modules/q/q.js, function=null,
 line=880, method=null, native=false, column=9,
 file=/home/ec2-user/js-proxy/node_modules/q/q.js,
 function=makePromise.promiseSend, line=553, method=promiseSend,
 native=false, column=35,
 file=/home/ec2-user/js-proxy/node_modules/q/q.js, function=, line=465,
 method=null, native=false, column=38, file=node.js,
 function=EventEmitter._tickCallback, line=190, method=_tickCallback,
 native=false], stack=[Error: This socket is closed.,     at
 Socket._write (net.js:474:19),     at Socket.write (net.js:466:15),   
 at /home/ec2-user/js-proxy/app.js:408:24,     at _fulfilled
 (/home/ec2-user/js-proxy/node_modules/q/q.js:860:32),     at
 /home/ec2-user/js-proxy/node_modules/q/q.js:881:34,     at
 makePromise.promiseSend
 (/home/ec2-user/js-proxy/node_modules/q/q.js:553:9),     at
 /home/ec2-user/js-proxy/node_modules/q/q.js:880:28,     at
 makePromise.promiseSend
 (/home/ec2-user/js-proxy/node_modules/q/q.js:553:9),     at
 Array.<anonymous>
 (/home/ec2-user/js-proxy/node_modules/q/q.js:465:35),     at
 EventEmitter._tickCallback (node.js:190:38)]

更新:我参加了Node.js讲座,并学习了一些关于异常处理的知识;显然它很糟糕而且被忽视了。它正在进行中。

1 个答案:

答案 0 :(得分:1)

最简单的修复似乎是在写入之前检查套接字是否可写。您还可以检查被破坏的财产。这个东西都是在socket关闭事件中设置的。

promise.then(function (val) {
  if( sock.writable ){
    sock.write(val + conf.proxy.tcpDelimiter);
  } else {
    logger.info('this works');
  }
})
.fail(function (error) {});