Does Koa safely handle errors?

前提是你 提交于 2019-12-08 04:55:34

问题


The Nodejs API states...

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.

However Koa traps errors and avoids exiting the nodejs process. What enables Koa to safely flout this advice?


回答1:


There are primarily two cases where koa can not safely handle errors.

Thrown errors on different ticks:

app.use(function* () {
  setImmediate(function () {
    throw new Error('boom')
  })
})

Emitter errors that are not set as response.body=:

app.use(function* () {
  this.response.body = stream.pipe(zlib.createGzip())
})

Any function or library that does the first case is malformed and should not be used. If the function/library uses promises and/or callbacks correctly, it will never happen.

For emitters, simply always set each stream as the body (or use middleware):

 app.use(function* () {
  this.response.body = stream
  this.response.body = this.response.body.pipe(zlib.createGzip())
})

Koa does this by allowing you to use try/catch on "async" stuff, specifically callbacks and promises. You can't, however, try/catch an error thrown on a different tick or an emitter.



来源:https://stackoverflow.com/questions/27532318/does-koa-safely-handle-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!