如何因致命错误或类似错误而失败

How to fail with a fatal error or similar?

本文关键字:错误 失败 何因 致命错误      更新时间:2023-09-26

是否可以在特定条件下终止脚本并显示特定的错误消息?例外情况不是一种选择,因为它们可以被捕获,从而避免终止。

更新:

我更喜欢通用的方法,但如果没有,那就是浏览器内JavaScript。错误应该是静默的,并且错误消息应该只进入浏览器错误日志。

如果您的代码在try语句中,并且您正在寻找一种方法来阻止某些错误,那么我认为您正在寻找finally块:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-美国&redirectslug=JavaScript%2FGuide%2FStatements#The_finally_Block

从该网站(并将烦人的alert()编辑为console.log()),您可以找到以下示例:

function f() {
    try {
        console.log(0);
        throw "bogus";
    } catch(e) {
        console.log(1);
        return true; // this return statement is suspended until finally block has completed
        console.log(2); // not reachable
    } finally {
        console.log(3);
        return false; // overwrites the previous "return"
        console.log(4); // not reachable
    }
    // "return false" is executed now
    console.log(5); // not reachable
}
f(); // alerts 0, 1, 3; returns false

不幸的是,我只能通过以下丑陋的解决方法来实现这一点:

var failWithFatalError; // A non-existent function
console.error (message + ' in ' + homebrewStackTraceFunction());
failWithFatalError();