egg icon indicating copy to clipboard operation
egg copied to clipboard

app.httpclient.on如何实现抛出异常被外部统一捕获

Open bymaxchen opened this issue 7 years ago • 7 comments

app.js app.httpclient.on('response', result => { if (result.res.code < 0) { throw new Error('error'); } });

middleware/error-handler.js try { yield next; } catch (err) { console.log(err) }

这里错误无法被捕获。进程反而会crash,抛出uncaughtException。

bymaxchen avatar Dec 17 '18 09:12 bymaxchen

看来对 Node 的 callback error 处理不是很熟悉啊,在一个回调里面抛错,必然捕获不到啊。

你的原始需求是啥

atian25 avatar Dec 17 '18 09:12 atian25

app.httpclient.on('response', result => {
  if (result.res.code < 0) { app.logger.error(new Error('error')); } 
});

改为直接打错误,这个已经不在洋葱圈里了。

popomore avatar Dec 17 '18 11:12 popomore

Hello @bymaxchen. Please provide a reproducible example following the instruction.

Issues labeled by Need Reproduce will be closed if no activities in 7 days.


@bymaxchen,请根据这个说明提供最小可复现代码。

如果在 7 天内没有进展会被自动关闭。

egg-bot avatar Dec 18 '18 02:12 egg-bot

@atian25
原始需求就是调用外部请求,如果响应的code小于0,就直接抛异常,结束后面的流程,然后把外部调用的错误码透传给前端。

bymaxchen avatar Dec 19 '18 08:12 bymaxchen

  1. 直接使用 curl 调用,判断 code 然后 throw
  2. 如果要通用处理就封装一个 service。

popomore avatar Dec 19 '18 08:12 popomore

@popomore 好的,谢谢解答。

bymaxchen avatar Dec 19 '18 08:12 bymaxchen

// app/extend/context.js
module.exports = {
  async sendRPC(url, options) {
    const result = await this.curl(url, options);
    if (xxxx) throw new Error('xxxx');
    return result;
  }
};

atian25 avatar Dec 19 '18 09:12 atian25