【问题标题】:Node.js - Domain per Express request, inside another domainNode.js - 每个 Express 请求的域,在另一个域内
【发布时间】:2013-07-17 18:48:18
【问题描述】:

Node.js 中的错误处理。啊!

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

Cluster -> Worker -> Server Domain -> Express Request Domain

因此,如果由于有人在登录表单上拼错了自己的姓名而将错误抛出到调用堆栈的 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/,得到一个不错的小“哎呀”错误,并在控制台中看到“触发请求错误”和错误堆栈。

实际发生了什么......

我在浏览器和控制台中都得到了这个响应......

ReferenceError: this_function_does_not_exist 未定义 在 /Stuff/test.js:38:13 在回调(/Stuff/node_modules/express/lib/router/index.js:161:37) 在参数处(/Stuff/node_modules/express/lib/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)

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

【问题讨论】:

    标签: javascript node.js express connect npm


    【解决方案1】:

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

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

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

    那么域就会抓取它。

    【讨论】:

    • 感谢您指出原因 - 但您实际上并没有提供示例代码来说明“它需要如何从当前调用堆栈中取出”
    • 如果它是当前调用堆栈的一部分,Express 会捕获它,并且它不会“冒泡”到域处理程序。麻烦的是,我们并不总是知道什么时候会发生,它可能在调用 res.send()/将任何内容返回给浏览器的函数之外。因此,通过使用 process.nextTick,我们有效地绕过了 Express 堆栈,并在当前调用堆栈的 END 处独立运行它......但仍在域的上下文中。因此,会触发一个错误,域将其拾取,并将其扔回 res.send,它位于我的原始示例代码的上下文中。这有帮助吗?
    • 谢谢 - 我听你说的。你想在 nextTick() 中抛出异常。
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    相关资源
    最近更新 更多