【发布时间】:2019-04-04 16:22:13
【问题描述】:
我确实使用第三方 API 来管理身份验证操作。
可用的方法返回promise,假设一个createUser方法,我可以这样调用:
this.auth.createUser(data).then(() => alert('user created'));
到目前为止还可以。
如果我确实发送了无效数据,或者如果我打破了一些先决条件,API 会抛出一些带有大量数据和信息的大错误。问题是这些错误对用户不友好。
我正在尝试包装这些方法,因此我可以抛出一个已知错误(特定标记)并向用户提供更好的消息,但到目前为止我无法做到。
我已经构建了这个 sn-p:
class Auth {
createUser(...args) {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.log(...args);
throw new Error('auth service throws some error with a lot of details and info not user friendly');
}, 3000);
});
}
log(...args) { console.log('this', ...args) }
}
const auth = new Auth();
Object.keys(auth).forEach(key => {
if (typeof auth[key] === 'function') {
const originalFunction = auth[key];
auth[key] = function() {
try {
return originalFunction.apply(this, arguments);
} catch (e) {
this.log('error', e);
throw new Error('error-auth-' + nameFunctionAsTag(key));
}
};
} else {
console.log(typeof auth[key]);
}
});
function nameFunctionAsTag(name) {
return name.replace(/(?!^)[A-Z]/g, c => '-' + c.toLowerCase());
}
auth.log('auth service');
auth.createUser(1, 2, 3, 4, 5);
// expected: error-auth-create-user
// received: auth service throws some error with a lot of details and info not user friendly
正如在最后两行代码中所评论的那样,我预计会发现错误并收到error-auth-create-user,但我不明白为什么它不起作用。
任何帮助表示赞赏,在此先感谢。
【问题讨论】:
-
在 setTimeout 中的 throw 与在 new Promise 中的 throw 是不同的上下文。改用拒绝
-
@charlietfl 我明白你的意思。但是假设 API 期望的某个字符串参数为 null,并且 API 尝试
null.toLowerCase(),它会像我的示例一样抛出,不是吗?我的意思是,如何在我的代码中捕获所有可能的错误/拒绝? -
@charlietfl 现在我没明白你的意思……我已经用过 try catch。我无法更改 API 代码(它是第三方代码),上面的
createUser只是我为模拟 API 错误而构建的一个示例。 -
谢谢大家:)
标签: javascript