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
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

Incredible Demos

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

  • By
    Digg-Style Dynamic Share Widget Using the Dojo Toolkit

    I've always seen Digg as a very progressive website. Digg uses experimental, ajaxified methods for comments and mission-critical functions. One nice touch Digg has added to their website is their hover share widget. Here's how to implement that functionality on your site...

Discussion

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