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

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • By
    Create Twitter-Style Dropdowns Using MooTools

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    Create a Context Menu with Dojo and Dijit

    Context menus, used in the right type of web application, can be invaluable.  They provide shortcut methods to different functionality within the application and, with just a right click, they are readily available.  Dojo's Dijit frameworks provides an easy way to create stylish, flexible context...

Discussion

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