既然我们可以throw在Javascript中使用关键字抛出任何内容,那么我们不能直接抛出错误消息字符串吗?
有谁知道这有什么捕获?
让我为此添加一些背景:很多时候,在JavaScript世界中,人们依赖于参数检查而不是使用try-catch机制,所以只抛出致命错误才有意义throw.仍然,为了能够捕获一些系统错误,我必须为我自己的错误使用不同的类,而不是创建Error的子类,我想我应该只使用String.
当我运行以下程序时
async function functionOne() {
throw new Error('Error here prints the complete stack');
await new Promise((resolve) => {
setTimeout(() => { resolve(); }, 1000);
});
}
async function functionTwo() {
await functionOne();
}
async function functionThree() {
await functionTwo();
}
functionThree()
.catch((error) => {
console.error(error);
});
Run Code Online (Sandbox Code Playgroud)
我得到以下输出,该输出通过各种调用的函数打印堆栈
Error: Error here prints the complete stack
at functionOne (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:3:9)
at functionTwo (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:11:9)
at functionThree (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:15:9)
at Object.<anonymous> (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:18:1)
at Module._compile (module.js:612:30)
at Object.Module._extensions..js (module.js:623:10)
at Module.load (module.js:531:32)
at tryModuleLoad (module.js:494:12)
at Function.Module._load …Run Code Online (Sandbox Code Playgroud)