gpt4 book ai didi

node.js - 在 Node/Express 的异步函数中捕获错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:20 32 4
gpt4 key购买 nike

在 Express next()res.send() 从中间件或路由处理程序?考虑以下代码:

app.use('/throw-error', (req, res) => {
setTimeout(() => {
throw new Error('Async error causes thread death')
}, 500)

res.send('This thread is going to die...')
})

它将执行并向浏览器发送“This thread is going to die...”。半秒后,它还会使正在运行的 Node 线程崩溃。如果您碰巧正在运行一个使用 Node 的 cluster 模块的应用程序,它可能会启动一个新线程,但它仍然会死掉.您可能会在日志中看到类似这样的内容:

::1 [2019-07-17T18:54:55.142Z] - [71700] 4.740 ms "GET /throw-error" 200 -
/Users/moryl/Projects/crashtest/express.js:66
throw new Error('Async error causes thread death')
^

Error: Async error causes thread death
at Timeout.setTimeout [as _onTimeout] (/Users/moryl/Projects/InSight/sources/server/config/express.js:66:13)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)

那个线程现在已经死了。

我的问题是,您到底是如何处理超出正常请求范围的(可能未知)异步错误的,无论是设计上的还是错误的代码?如何防止线程死亡?

我不想被告知我不应该在异步调用中做这种事情。我知道这个。我正在尝试编写防御性代码来捕获其他人编写的“坏东西”。

最佳答案

这已记录在 express error handling doc 中:

You must catch errors that occur in asynchronous code invoked by route handlers or middleware and pass them to Express for processing. For example:

app.get('/', function (req, res, next) {
setTimeout(function () {
try {
throw new Error('BROKEN')
} catch (err) {
next(err)
}
}, 100)
})

The above example uses a try...catch block to catch errors in the asynchronous code and pass them to Express. If the try...catch block were omitted, Express would not catch the error since it is not part of the synchronous handler code.

因此,基本上您需要try..catch 路线。 (例子基本一致,巧了)

关于node.js - 在 Node/Express 的异步函数中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082615/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com