Safe Function Calls with attempt
As browser implement new APIs, the truth is that though the APIs provide more power, I'd argue they bring about more volatility. Whether it's the API that's the issue or us trying to use it, you're bound to run into errors which may break parts of your app. Crap. And a try/catch blocks everywhere? Bleh. That's why I use an attempt
function in such cases: it keeps the code cleaner and with less side effects.
The JavaScript
What we'll do is essentially call the function for the user, catching any crap that comes along:
function attempt(fn, args, binding) { try { return fn.apply(binding, args); } catch(e) { console.log('Exception, fix me please', e); } } // Use it! attempt(function() { /* volatile stuff */ }, ['argOne', someVar], this);
Provide the function, args, and binding and you're all set. You can use anonymous functions, named functions, whatever. And you don't need to add your own try/catch blocks everywhere. Nothing groundbreaking in the code above but it's safe and easy!