错误后如何允许代码继续执行[JS]

时间:2020-03-10 17:41:22

标签: javascript error-handling

所以,我正在建立一个网站。它检查URL查询。如果没有,我的所有代码都会停止,但是即使有错误,我也希望代码能够执行。这是我当前的代码:

if (getUrlArg('foo') == "bar") { //do stuff }

但是,如果URL栏中没有“ Foo”,则会引发错误并停止执行脚本。即使网址列中没有'foo',我如何继续运行脚本?

编辑:

getUrlArg的代码是这样的:

function getUrlArg(argname) {
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  return urlParams.get(argname);
}

3 个答案:

答案 0 :(得分:1)

您有两种选择:

  1. 修改getUrlArg,以便在某些情况下不会抛出异常。也许是第二个可选参数defaultValue,如果它接收到它并且URL没有参数(它返回defaultValue则不抛出)。

  2. 在问题中的代码周围使用try / catch,忽略错误。

我会和#1一起去。

下面是使用默认值的粗略草图(ES5):

function getUrlArg(name, defaultValue) {
    if (/*...the arg isn't there...*/) {
        if (typeof defaultValue !== "undefined") {
            return defaultValue;
        }
        throw new Error(/*...the error it's already throwing...*/);
    }
    return /*...the value that was found in the URL...*/;
}

然后在哪里使用它:

if (getUrlArg("foo", null) === "bar") { /*...do stuff...*/ }

或仅采用“可选”标志:

function getUrlArg(name, optional) {
    if (/*...the arg isn't there...*/) {
        if (optional) {
            return; // Returns `undefined`
        }
        throw new Error(/*...the error it's already throwing...*/);
    }
    return /*...the value that was found in the URL...*/;
}

然后在哪里使用它:

if (getUrlArg("foo", true) === "bar") { /*...do stuff...*/ }

答案 1 :(得分:0)

您可以为此使用“尝试捕获块”

try {
 //code with error
} catch (err) {
 //code to execute after error is caught
}

答案 2 :(得分:0)

好吧,我能想到的最简单的方法就是条件有所不同:

if (foo && getUrlArg(foo) == "bar") {
  // do stuff
} else {
  // go on and do other stuff
}

当然,您可以在else语句中添加更复杂的内容。如果未设置foo,则脚本应继续使用您在else中输入的内容。否则,您也可以将foo !== null添加到if中。承诺很好,但是其实现取决于您要实现的目标。

相关问题