express-ws是沉默错误

时间:2017-05-02 11:00:13

标签: javascript node.js express

我在节点应用程序中使用express和express-ws。但是,express-ws似乎是在调整错误,因此很难调试我的代码。

我已将代码缩减到以下仍然会重现问题:

// configure express
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

// set up routes

app.get('/', function(req, res) {
    console.log("GET");
    nonExistingFunction(); // Called to demonstrate a traceback is provided.
});

app.ws('/', function(ws, req){    
    console.log("WS");
    nonExistingFunction(); // Called to demonstrate this error is silenced.
});

// start service
app.listen(90);

当我从浏览器获取时,控制台显示“GET”日志消息,然后是回溯(如预期的那样)。即;

GET
ReferenceError: nonExistingFunction is not defined
    at C:\(project dir)\server.js:11:9
    at Layer.handle [as handle_request] (C:\(project dir)\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\(project dir)\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\(project dir)\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\(project dir)\node_modules\express\lib\router\layer.js:95:5)
    at C:\(project dir)\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\(project dir)\node_modules\express\lib\router\index.js:335:12)
    at next (C:\(project dir)\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\(project dir)\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\(project dir)\node_modules\express\lib\router\layer.js:95:5)

当我通过Websocket连接时,控制台只显示“WS”日志消息 -  没有追溯。即;

WS

默认情况下express-ws是否会出错?有没有办法把它关掉?

1 个答案:

答案 0 :(得分:0)

我有一个解决方案。

Express有自己的默认错误处理程序,它将回溯输出到控制台,但允许应用程序继续运行。 Express-ws使用try-catch嵌套在wrap-middleware.js中执行相同操作。

  try {
    /* Unpack the `.ws` property and call the actual handler. */
    middleware(req.ws, req, next);
  } catch (err) {
    /* If an error is thrown, let's send that on to any error handling */
    next(err);
  }

但是,这似乎没有传递给默认的错误处理程序。因此,您可以为app指定错误处理程序中间件。这必须是链中的最后一个中间件。以下代码有点hacky,但无论HTTP或WS路由函数中是否发生错误,都会将回溯输出到控制台。

// configure express
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

// set up routes

app.get('/', function(req, res) {
    console.log("GET");
    nonExistingFunction(); // Called to demonstrate a traceback is provided.
});

app.ws('/', function(ws, req){    
    console.log("WS");
    nonExistingFunction(); // Called to demonstrate this error is no longer silenced :)
});

// set up error handler

function errorHandler (err, req, res, next) {
    if(req.ws){
        console.error("ERROR from WS route - ", err);
    } else {
        console.error(err);
        res.setHeader('Content-Type', 'text/plain');
        res.status(500).send(err.stack);
    }
}
app.use(errorHandler);

// start service
app.listen(90);