我确实使用第三方 API 来管理身份验证操作。
可用的方法返回 Promise,假设有一个 createUser
方法,我可以这样调用它:
this.auth.createUser(data).then(() => alert('user created'));
到目前为止还好。
如果我确实发送了无效数据,或者如果我违反了某些先决条件,则 API 会抛出一些带有大量数据和信息的大错误。问题是这些错误对用户不友好。
我正在尝试包装这些方法,因此我可以抛出已知错误(特定标记)并向用户提供更好的消息,但到目前为止我无法做到这一点。
我构建了这个片段:
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
,但我不明白为什么它不起作用。
感谢任何帮助,提前致谢。
最佳答案
在promise中使用resolve和reject。
这里(您的代码):
try {
return originalFunction.apply(this, arguments); // asynchronous because of setTimeOut
} catch (e) {
this.log('error', e);
throw new Error('error-auth-' + nameFunctionAsTag(key));
}
// 3 second later, trigger exception out of try/catch statement
你可以做什么:
function asyncError(){
return new Promise(function(resolve, reject){
// ... code
reject(new Error('Error ...'));
// ... code
})
}
async function test(){
try{
const experiment = await asyncError();
}
catch(e){
console.log(e)
}
}
其他方式(无需等待即可捕获):
function test2(){
asyncError().catch((e) => console.log(e));
}
关于javascript - 如何包装来自第三方 api 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55520801/