3

Node.js 中的错误处理 啊!

我正在尝试像这样布局一个基本的 Node 应用程序......

集群 -> Worker -> 服务器域 -> 快速请求域

因此,如果由于有人在登录表单上拼错了自己的姓名而导致调用堆栈的 18 层深处出现错误,则整个服务器不会崩溃。

下面是一些模拟工人部分的基本代码:

var domain, server;

domain = require('domain');
server = domain.create();

server.on('error', function(e) {
    console.log('total meltdown...', e.stack);
});

server.run(function() {

    var express = require('express')();

    express.configure(function() {

        // Domain on EVERY request
        express.use(function(req, res, next) {
            var d = domain.create();

            d.on('error', function(e) {
                console.log('fired REQUEST error', e.stack);
                next(e);
            });

            d.run(next);

        });

        // Generic error handler
        express.use(function(e, req, res, next) {
            res.status(500);
            res.end('oops');
        });

        // Serve the request with a blatent error
        express.get('/', function(req, res) {

            this_function_does_not_exist();
            res.end('we will never get here');

        });
    });

    // Fire 'er up
    express.listen(3000);
});

我所期待的...

我 curl http://localhost:3000/,得到一个不错的小 'oops' 错误,并在控制台中看到 'fired REQUEST error' 和错误堆栈。

究竟发生了什么...

我把它作为浏览器响应,在控制台中......

ReferenceError:this_function_does_not_exist 未在参数 (/Stuff/node_modules/express/lib 的回调 (/Stuff/node_modules/express/lib/router/index.js:161:37) 处的 /Stuff/test.js:38:13 处定义/router/index.js:135:11) 通过 (/Stuff/node_modules/express/lib/router/index.js:142:5) 在 Router._dispatch (/Stuff/node_modules/express/lib/router/index .js:170:5) 在 Object.router (/Stuff/node_modules/express/lib/router/index.js:33:10) 在下一个 (/Stuff/node_modules/express/node_modules/connect/lib/proto.js :190:15) 在下一个 (/Stuff/node_modules/express/node_modules/connect/lib/proto.js:192:9) 在 b (domain.js:183:18) 在 Domain.run (domain.js:123 :23)

现在为什么它会去做这样的事情呢?

4

1 回答 1

2

好的,解决了 - Express 有一个 try/catch 块,它首先到达我不存在的函数调用。

要让域捕获它,它需要从当前调用堆栈中取出,比如......

        process.nextTick(function() {
            this_function_does_not_exist();
            res.end('we will never get here');
        });

然后域将抓住它。

于 2013-07-21T08:37:45.897 回答