Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Helpful error handling in jQuery

Posted by Dave Mahon

If you’re going to build a reusable tool, you’re going to want to be able to detect, handle and report error messages in a nice, clean way. It will make you and any other dev happy.

The cleanest way of handling genuine errors for developers using your tool – namely, invalid input sent to a function in the library – is to log it to the console. Doing so is refreshingly straightforward:

var err = new Error();
err.name = "jQuery.widget.UI.clicker.range()";
err.message = "Both values must be numeric to assign range";
throw(err);

This snippet comes straight from the widget I threw together. I encourage you to make the name as detailed as possible. It will make debugging so much easier. You can even pinpoint the exact point of error if the problem was say, an invalid query syntax. (Handy during the development phase; not so much in a production environment!)


Leave a Reply