Koa是否可以安全地处理错误? [英] Does Koa safely handle errors?

查看:80
本文介绍了Koa是否可以安全地处理错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Nodejs API 状态...

从本质上讲,throw在JavaScript中是如何工作的,几乎有 从来没有任何方法可以安全地捡起您离开的地方",而不会泄漏 引用,或创建其他未定义的脆性状态.

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放心提出了这个建议?

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

推荐答案

主要有两种情况,koa无法安全地处理错误.

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')
  })
})

未设置为response.body=的发射器错误:

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

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

任何执行第一种情况的函数或库都格式不正确,不应使用.如果函数/库正确使用了Promise和/或回调,它将永远不会发生.

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通过允许您对异步"内容(特别是回调和Promise)使用try/catch来做到这一点.但是,您不能尝试/捕获在其他刻度线或发射器上引发的错误.

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.

这篇关于Koa是否可以安全地处理错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆