CHAPTER NINE

Error Handling

If you’re like me, you probably don’t think much about how you’ll handle errors until they start popping up on a regular basis. Programmers tend to write code as if there will never be any errors, and then spend the rest of their time tracking down errors they’ve caused. This inclination is totally natural. No one starts out on a project thinking about all the ways they will do something wrong. You start out believing you know the right way to do it and then are unpleasantly surprised as errors start to pop up.

But what if you changed the thought process? Instead of assuming that errors won’t happen, assume that they will. How would that change your approach to writing code? That’s precisely what this chapter is about: thinking about and planning for the errors that will inevitably occur in your JavaScript.

Assume Your Code Will Fail

If an error is possible, someone will make it. The designer must assume that all possible errors will occur and design so as to minimize the chance of the error in the first place, or its effects once it gets made.

Donald A. Norman, The Design of Everyday Things

The first step to good error handling is to accept that your code will fail at some point. That may be because of improper use, or proper use that you didn’t plan for. Regardless, your code will fail at some point in time. Given that, what can you do to make your code more robust? What are the things you can do, right now, to make ...

Get Beautiful JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.