So, I am making a website. It checks for a URL query. If there isn't one, all my code stops, but I want code to execute even if there is an error. Here is my current code:
if (getUrlArg('foo') == "bar") { //do stuff }
But if there is no 'Foo' in the URL bar, it throws an error and stops executing the script. How can I continue running the script even if there is no 'foo' in the URL bar?
edit:
The code for getUrlArg is this:
function getUrlArg(argname) {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
return urlParams.get(argname);
}
You have two choices:
Modify getUrlArg
so it doesn't throw in some situations. Perhaps an optional second argument defaultValue
and it doesn't throw if it receives it and the URL doesn't have the argument (it returns defaultValue
instead).
Use try
/ catch
around the code in the question, ignoring the error.
I'd go with #1.
Here's a rough sketch (ES5) of taking a default value:
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...*/;
}
then where you use it:
if (getUrlArg("foo", null) === "bar") { /*...do stuff...*/ }
Or just take an "optional" flag:
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...*/;
}
then where you use it:
if (getUrlArg("foo", true) === "bar") { /*...do stuff...*/ }
You can use a "try catch block for this"
try {
//code with error
} catch (err) {
//code to execute after error is caught
}
Well, the easiest way I can imagine is a bit different condition:
if (foo && getUrlArg(foo) == "bar") {
// do stuff
} else {
// go on and do other stuff
}
Of course, you can add more complex stuff in the else
statement. If foo
is unset, the script should go on with what you put in else
. Otherwise, you can add foo !== null
too to your if
. Promises are great, but their implementation depends on what you want to achieve.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.