抛出前一帧信息

时间:2018-11-18 11:36:25

标签: javascript exception-handling throw

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

2 个答案:

答案 0 :(得分:1)

在许多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

答案 1 :(得分:0)

我会考虑只用try/catch包装语句,如下所示,它仍然不会指向确切的行,但是取决于您的使用,它可以是紧密匹配的,并且您的函数保持不变:

function api(cmd) {
        if (cmd > 5 ) throw `Unknown command: ${cmd}`;
        console.log('coommand', cmd);
    }

    try {
        api(3);
        api(10);
    } catch(e) {
        throw e;
    }