function api(cmd) {
if (cmd > 5) throw 'unknown command'
console.log('executing the command', cmd)
}
api(2)
api(7)
如果执行上面的代码,将会打印这个漂亮的错误消息:
executing the command 2
test.js:2
if (cmd > 5) throw 'unknown command'
^
unknown command
我怎样才能(我可以吗?)让错误消息返回一帧并显示它:
executing the command 2
test.js:7
api(7)
^
unknown command
最佳答案
在许多 JavaScript 环境中,当发生错误时,您可以获得完整的“祖先”函数调用堆栈(及其行号),前提是您使用正确的 Error
对象引发错误。
因此将代码更改如下:
if (cmd > 5) throw new Error('unknown command');
另一种可能性是改变函数的使用方式。例如,它可以返回一个在任何事情发生之前必须调用的函数:
function api(cmd) {
if (cmd > 5) return; // Return undefined
// If all OK, return a function that does the job
return function() {
console.log('executing the command', cmd);
// ....
}
}
// The "contract" changed, so the caller must add parentheses:
api(2)()
api(7)() // TypeError: api() is not a function
关于javascript - 抛出前一帧信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360419/