请求管道上的错误处理

ion*_*ure 23 javascript request node.js

我在nodejs上编写了简单的代理,它看起来像

var request = require( 'request' );
app.all( '/proxy/*', function( req, res ){
    req.pipe( request({
        url: config.backendUrl + req.params[0],
        qs: req.query,
        method: req.method
    })).pipe( res );
});
Run Code Online (Sandbox Code Playgroud)

如果远程主机可用,它可以正常工作,但如果远程主机不可用,则整个节点服务器会因未处理的异常而崩溃

stream.js:94                                               
      throw er; // Unhandled stream error in pipe.         
            ^                                              
Error: connect ECONNREFUSED                                
    at errnoException (net.js:901:11)                      
    at Object.afterConnect [as oncomplete] (net.js:892:19) 
Run Code Online (Sandbox Code Playgroud)

我该如何处理这些错误?

Tom*_*ant 31

查看文档(https://github.com/mikeal/request),您应该可以执行以下操作:

您可以根据请求使用可选的回调参数,例如:

app.all( '/proxy/*', function( req, res ){
  req.pipe( request({
      url: config.backendUrl + req.params[0],
      qs: req.query,
      method: req.method
  }, function(error, response, body){
    if (error.code === 'ECONNREFUSED'){
      console.error('Refused connection');
    } else { 
      throw error; 
    }
  })).pipe( res );
});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下内容捕获未捕获的异常:

process.on('uncaughtException', function(err){
  console.error('uncaughtException: ' + err.message);
  console.error(err.stack);
  process.exit(1);             // exit with error
});
Run Code Online (Sandbox Code Playgroud)