Does Koa safely handle errors?

老子叫甜甜 提交于 2019-12-08 21:01:46

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.

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