Question

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);

};

JSBIN

Was it helpful?

Solution

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;
}

OTHER TIPS

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
  • try/catch is only used by the method that believes it can handle the exception
  • if no exception happens, the code reads linearly and cleanly, and the following line never has to worry about whether the previous line succeeded
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top