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 @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Incredible Demos

  • By
    Drag & Drop Elements to the Trash with MooTools 1.2

    Everyone loves dragging garbage files from their desktop into their trash can. There's a certain amount of irony in doing something on your computer that you also do in real life. It's also a quick way to get rid of things. That's...

  • By
    QuickBoxes for Dojo

    Adding to my mental portfolio is important to me. First came MooTools, then jQuery, and now Dojo. I speak often with Peter Higgins of Dojo fame and decided it was time to step into his world. I chose a simple but useful plugin...

Discussion

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