1

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?

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189

1 Answers1

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.

Jonathan Ong
  • 19,927
  • 17
  • 79
  • 118