CNode

koa1里多错误的捕获,有些问题 ,有什么更好的方法?

问答
Wwangshiyang3035884发布于10 年前最后回复10 年前5 回复4653 浏览0 收藏

//问题1: 捕获错误 代码报错,只支持构造器方法 app.use('error', function(err){ console.log(err.status); if (this.status == 404) { yield this.render('404', { message : this.message }); } else if(this.status == 500){ yield this.render('500', { message : this.message }); } }); // 问题2 只能捕捉地址栏路径错误,捕捉不到代码错误 app.use(function *notFound(next, ctx) { if (this.status == 404) { yield this.render('404', { message : this.message }); } else if(this.status == 500){ yield this.render('500', { message : this.message }); }else { yield next; } });

查看回复

回复 (5)

N
ncuzp#1·10 年前

可以试试try catch啊

F
FoghostCn#2·10 年前

可以在最前面的中间件中统一try catch,其余的逻辑里面只管throw

E
elrrrrrrr#4·10 年前

问题1: 函数里用了 yield ,所以需要 generator function 推荐 ref

  1. 先自定义一个 try catch 的中间件
  2. 其余中间件直接抛出异常即可
J
Jarvin-Guan#5·10 年前

app.use(function* (next) { try { yield next; } catch (err) { if (err.external) { let e = { code: err.code, message: err.message }; if (err.extra) e.extra = err.extra; this.send(e); } else { logger.error(err.stack); logger.error(err.message); this.send({ code: 500, message: ‘服务器暂时不可用’ }); } } })

参与回复
登录后即可参与回复。登录