1

When handling user input (in a JS library, not form text), it's easy to throw type-related errors, when a user supplies a non-function and you expected a function for instance. Suppose I have a function callFn that takes a function and arguments to supply to it and evaluates the function or returns null if it fails to, I can either use try-catch or simply check that the input is a function before calling:

callFn(fn, args) {
    return fn instanceof Function ? fn.apply(window, args) : null;
}
//vs
callFn(fn, args) {
    var ret = null;
    try {
        ret = fn.apply(window, args);
    }
    catch (e) {
        console.error(e) //Still display error for debugging
    }
    return ret;
}

What are the advantages and disadvantages of both ways? Am I correct in the following:

Any the biggest one and why I'm considering switching to try-catch

  • If the user supplies an object with 10+ fields and many of those fields are functions to evaluate or objects to access, a single try-catch statement will suffice if the function returns the same for any error, but the error preventing way would have to 10 - 20 instanceof/typeof statements; thus try-catch is much more readable (and faster to write).

I'm asking since I hardly ever see try-catch, and was unsure if there is a better (good) reason for it to be bad practice.

Community
  • 1
  • 1
Tahsis Claus
  • 1,879
  • 1
  • 15
  • 27
  • If you're writing a library you usually don't want to try-catch the errors away: if the developer is passing you rubbish or using your code wrong they should notified by errors. If you wrap things up in a try-catch there will be no errors and the code will be harder to debug. – Etheryte Nov 04 '15 at 17:04
  • That's the purpose of logging the error. Sometimes it's useful to have a function return without errors even with bad input (pretty much every lodash function). – Tahsis Claus Nov 04 '15 at 19:01

0 Answers0