Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
bymaxchen opened this issue Dec 17, 2018 · 7 comments
Closed

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

bymaxchen opened this issue Dec 17, 2018 · 7 comments

Comments

@bymaxchen
Copy link

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。

@atian25
Copy link
Member

atian25 commented Dec 17, 2018

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

你的原始需求是啥

@popomore
Copy link
Member

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

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

@egg-bot
Copy link

egg-bot commented Dec 18, 2018

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 天内没有进展会被自动关闭。

@bymaxchen
Copy link
Author

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

@popomore
Copy link
Member

popomore commented Dec 19, 2018

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

@popomore popomore pinned this issue Dec 19, 2018
@popomore popomore unpinned this issue Dec 19, 2018
@bymaxchen
Copy link
Author

@popomore 好的,谢谢解答。

@atian25
Copy link
Member

atian25 commented Dec 19, 2018

// 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 atian25 closed this as completed Dec 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants