【发布时间】:2019-04-10 17:08:47
【问题描述】:
我在一些网站中读到 express.js 中的“异步代码中任何未捕获的错误都可能导致 HTTP 服务器崩溃导致 DoS”。 我已经做了这个例子来检查它,但我想知道为什么如果错误发生在快速回调中,服务器不会崩溃,但如果它发生在 setTimeout() 函数中,服务器就会崩溃。
这两个示例中的异步代码中是否都发生了错误,或者其中一个不是异步的,我弄错了? 为什么某些异步代码中未捕获的错误会导致服务器崩溃而其他异步代码中不会?
var express = require("express");
var app = express();
http: app.get("/e1", (req, res, next) => {
let p = req.query.p;
let pn = parseInt(p, 10);
//If the error happens here the server does not crashes
let s = pn + y; // y does not exist, so an error occurs
res.send("hi");
});
http: app.get("/e2", (req, res, next) => {
let p = req.query.p;
let pn = parseInt(p, 10);
setTimeout(() => {
//If the error happens here the server crashes
let s = pn + y; // y does not exist, so an error occurs
}, 100);
res.send("hi");
});
app.listen(3000, function() {
console.log("Example app listening on port 3000!");
});
【问题讨论】:
-
验证输入并使用 try/catch
-
express是否默认处理错误?
标签: javascript node.js asynchronous error-handling crash