Safe Function Calls with attempt

By  on  

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!

Recent Features

Incredible Demos

  • By
    MooTools’ AutoCompleter Plugin

    One of the famous MooTools plugins is Harald Kirschner's AutoCompleter plugin. AutoCompleter takes a term input by the user and searches for matches -- an obviously help to the user. Here's how to make the most of Harald's great plugin. The XHTML All we...

  • By
    Chris Coyier’s Favorite CodePen Demos IV

    Did you know you can triple-heart things on CodePen? We’ve had that little not-so-hidden feature forever. You can click that little heart button on any Pen (or Project, Collection, or Post) on CodePen to show the creator a little love, but you can click it again...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!