Nodejs API州...
By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state.
然而,Koa 会捕获错误并避免退出 Nodejs 进程。是什么让 Koa 能够安全地无视这个建议?
最佳答案
主要有两种情况导致 koa 无法安全地处理错误。
在不同的刻度上抛出错误:
app.use(function* () {
setImmediate(function () {
throw new Error('boom')
})
})
未设置为 response.body=
的发射器错误:
app.use(function* () {
this.response.body = stream.pipe(zlib.createGzip())
})
执行第一种情况的任何函数或库都是格式错误的,不应使用。如果函数/库正确使用 Promise 和/或回调,则这种情况永远不会发生。
对于发射器,只需始终将每个流设置为主体(或使用中间件):
app.use(function* () {
this.response.body = stream
this.response.body = this.response.body.pipe(zlib.createGzip())
})
Koa 通过允许您对“异步”内容(特别是回调和 promise )使用 try/catch 来实现这一点。但是,您无法尝试/捕获在不同的刻度或发射器上引发的错误。
关于node.js - Koa 是否安全地处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532318/