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
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    Comment Preview Using MooTools

    Comment previewing is an awesome addition to any blog. I've seen really simple comment previewing and some really complex comment previewing. The following is a tutorial on creating very basic comment previewing using MooTools. The XHTML You can set up your XHTML any way you'd like.

  • By
    dat.gui:  Exceptional JavaScript Interface Controller

    We all love trusted JavaScript frameworks like MooTools, jQuery, and Dojo, but there's a big push toward using focused micro-frameworks for smaller purposes. Of course, there are positives and negatives to using them.  Positives include smaller JS footprint (especially good for mobile) and less cruft, negatives...

Discussion

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