我对 Express 内置错误处理程序感到困惑。
我不提供自定义错误处理程序,但我确实通过 next(err)
传递错误,如文档所述,Express 仅记录 [object object]
字符串。
以下是一些简化的代码:
var express = require('express');
var app = express();
app.get('/', function(req, res){
next({})
});
app.listen(3000);
当我在终端中curl http://localhost:3000
时,刚刚得到[object object]
。
所以我的问题是:
[object object]
是什么意思?- 内置错误处理程序如何处理错误?
- 为什么错误堆栈没有输出?
最佳答案
Express使用 Node 模块finalhandler ,当在 next
处理程序中指定时,它也会处理错误。每次 next
中的 error
不是 null
或 undefined
时,它都会尝试从 error
对象 status
、headers
和 message
本身获取。与 [object Object]
响应相关,我猜,它是放置在 html
响应中的错误消息,如果消息的类型为 Object
,则在强制转换为 String
时,它会给出 [object Object]
作为结果。
当从错误中获取消息时,finalhandler
会查找 env(无论是否是生产环境),并根据该信息检索消息。如果在开发中(默认情况下),将从“error.stack”中检索消息,因此制作如下内容:
next(new Error('Unauthorized'));
将在express html错误响应中给出Unauthorized
,因为在开发环境中finalhandler
将查找“error.stack”作为消息。
在生产中,指定状态码,会根据状态码给出错误信息:
NODE_ENV=production node server.js
next({ status: 401 });
给予:
<title>Error</title>
</head>
<body>
<pre>Unauthorized</pre>
</body>
</html>
将空对象文字作为错误(正在开发中):
next({});
最终finalhandler
从error.stack
接收undefined
(当尝试从错误中提取消息时),然后调用error.toString()
。
Why is there no output about the error stack?
通过设置 debug 的环境变量可以收到一些有用的信息。 finalhendler
还使用 degub
模块。为了不让不必要的信息污染终端,它的命名空间可用于启用调试:
DEBUG=finalhandler node server.js
关于node.js - 表达抛出[object object]错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49423851/