koa1里多错误的捕获,有些问题 ,有什么更好的方法?
发布于 8 年前 作者 wangshiyang3035884 3945 次浏览 来自 问答

//问题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 回复

可以试试try catch啊

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

  1. 先自定义一个 try catch 的中间件
  2. 其余中间件直接抛出异常即可

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

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: ‘服务器暂时不可用’ }); } } })

回到顶部