【发布时间】:2021-09-21 03:57:23
【问题描述】:
我目前正在研究如何从 then catch 块中抛出异常。我想了解errorHandler() 函数内部的问题。
const errorHandler = function () {
try {
thisFunctionReturnsAnError().then(response => {
console.log(response);
});
} catch (e) {
console.log(e); //How to trigger this?
}
};
const thisFunctionReturnsAnError = function () {
return3()
.then(value => {
throw new Error('This is the error message.');
})
.catch(err => {
//return Promise.reject('this will get rejected');
throw err;
//this one should somehow got to the catch that is located in the errorHandler() function. How to do this?
//I know that this 'err' will be in the next catch block that is written here. This is not what i want.
});
};
const return3 = async function () {
return 3;
};
errorHandler();
我在 stackoverflow 上搜索了一段时间,但没有任何帮助。我确信这个问题经常被问到,但我找不到答案,很抱歉。
编辑: 在这里添加了另一个版本的代码,但它仍然不起作用
const errorHandler = async function () {
try {
thisFunctionReturnsAnError()
.then(response => console.log(response))
.catch(err => console.log(err));
} catch (e) {
//console.log(e); //How to trigger this?
}
};
const thisFunctionReturnsAnError = function () {
return3()
.then(value => {
throw new Error('This is the error message.');
})
.catch(err => {
return Promise.reject(`Message is: ${err}`);
});
};
const return3 = async function () {
return 3;
};
errorHandler();
我将收到以下错误消息: 未捕获(承诺中)消息是:错误:这是错误消息。
【问题讨论】:
-
异步方法的错误处理需要与传统方式不同,下面的链接可能对您有用。参考:itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a
-
感谢您的回答,但遗憾的是这并没有回答我的问题。您给定链接中的内容不处理我的情况。我投入了 .catch() 函数。您发布的网站未处理此问题。
标签: javascript exception try-catch