【问题标题】:Why sometimes error in async code makes the node.js server crash为什么有时异步代码中的错误会导致 node.js 服务器崩溃
【发布时间】: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


【解决方案1】:

如果我们考虑throw 和catch 在堆栈上操作,可能会变得很清楚:

throw:沿着堆栈向下直到找到处理程序,然后从那里继续。

catch 将错误处理程序添加到堆栈。

对于同步代码,可视化为:

 // Legend:
 -> function call
 <- function returns

 http.request -> express.handler -> [try] -> your function -> nested call -> Throw!
 <-            <-                   [catch] <-----------------------------------

现在,当您启动异步操作时,会在某个时候回调回调,并且该回调最终会在新堆栈上结束:

 // the current stack:
 http.request -> express.handler -> [try] -> your function -> start async action
 <-            <-                 <-       <-             <-

 // somewhen later, the timeout calls back
 timer -> your setTimeout callback -> nested call -> Throw!
 Crash! <-----------------------------------------------------

现在 Express 将 catch 处理程序附加到您的代码中的回调:

 Express.get = function(callback) {
   //...
   try {
     callback(req, res, next);
   } catch(error) {
    // handle error
   }
 };

这将处理错误,但只是同步错误(已简化,实际代码为 here)


现在应该怎么处理呢?

基本上:将每个回调包装成一个 Promise(因为这使得异步错误处理更容易):

 const delay = ms => new Promise(res => setTimeout(res, ms));

然后 await 你创建的每一个承诺,并将所有内容包装在 try / catch 中:

 app.get(async (req, res) => {
   try {
      await delay(2000);
      const p = q + d;
   } catch(error) {
     res.status(500).send("whoops");
  }
});

之所以有效,是因为await“保留堆栈”(但只是await 在嵌套调用中的async 函数之一,这就是为什么我们需要像Express 那样添加我们自己的try / catch不是回调调用中的await),因此嵌套的await ed 函数之一内部的错误将回退到我们的错误处理程序。

 http.request -> express.handler -> [async] -> [try] -> nested call -> [await]
 <-                     <-               <-
 // synchronous code returned, the [async] stack will be kept
 [async] -> [try] -> nested call -> [await]

// somewhen, the promise resolves, execution coninues:
[async] -> [try] -> nested call -> Throw!
<-       <- [catch]  <--------------

【讨论】:

  • 那么,你是说express路由处理函数回调是同步代码?那么,为什么在 express 文档中叫回调呢?
  • @v8rs 不,我不是这么说的。
  • 我不明白快速路由处理程序如何捕获错误
  • @v8rs 在回调调用周围带有 try { } catch(e) { } 块
  • 我还是不明白,我没有使用带有 express 回调的 try catch 块,但是 express 回调中发生的错误不会导致应用程序崩溃
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多