I'm trying to decode URLs that may be single or double percent encoded using decodeURIComponent()
. Because I don't want to get an "URI malformed"
when a string is attempted to be decoded that only contains %25
(5), I'm using this try/catch
block. Have I used the try/catch
block correctly? It seems to work, but I'm trying to understand if this is a best practice approach, or if I've over-complicated things.
var uriCleanup = function (str) {
var cln = function (str) {
try {
str = decodeURIComponent(str);
//try to decode the URI again
return cln(str);
} catch (e) {
//if error thrown, URI contains single percent symbol
//return the str as it was the last time it was decoded
return str;
}
};
return cln(str);
};
You do overcomplicate things: there's no need to use recursion here.
function uriCleanup(str) {
var cln = str;
try {
do {
cln = decodeURIComponent(str);
} while (cln !== str && (str = cln));
}
catch (e) {}
return cln;
}
It's not best practice. try/catch
you should use, and only use, for handling exceptional situations that interrupt the flow of code and break your ability to complete it. If you use it more generally, you wind up with a very powerful goto
-like structure with unwieldy use in your code.
try/catch is a harder structure to learn compared to if, else, while, etc., because it only really makes sense if you're working in a somewhat large code base, with modular library functions.
A simple example might be the function
var saveOrder = function(order) {
if(!order.confirmed) {
throw new Error("Please confirm you order.");
}
saveToMySQL(order);
};
//... somewhere else
try {
order = getOrderFromUser();
saveOrder(userOrder);
alert("Thank you for your order, continue shopping?");
}
catch(err) {
alert(err);
}
The points here are
saveOrder
throws because it cannot proceed
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.