[eggjs/egg]app.httpclient.on如何实现抛出异常被外部统一捕获

2025-11-04 175 views
4

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。

回答

5

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

你的原始需求是啥

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

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

7

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

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

@popomore 好的,谢谢解答。

4
// 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;
  }
};