app.httpclient.on如何实现抛出异常被外部统一捕获
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。
看来对 Node 的 callback error 处理不是很熟悉啊,在一个回调里面抛错,必然捕获不到啊。
你的原始需求是啥
app.httpclient.on('response', result => {
if (result.res.code < 0) { app.logger.error(new Error('error')); }
});
改为直接打错误,这个已经不在洋葱圈里了。
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 天内没有进展会被自动关闭。
@atian25
原始需求就是调用外部请求,如果响应的code小于0,就直接抛异常,结束后面的流程,然后把外部调用的错误码透传给前端。
- 直接使用 curl 调用,判断 code 然后 throw
- 如果要通用处理就封装一个 service。
@popomore 好的,谢谢解答。
// 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;
}
};