What are the best practices for JavaScript error handling?

I'm looking to start making my JavaScript a bit more error proof, and I'm finding plenty of documentation on using try, catch, finally, and throw, but I'm not finding a ton of advice from experts on when and where to throw errors.

  • Should every piece of code be wrapped in a try/catch?
  • Is there more advice like this on at what point errors ought to be caught?
  • Are there disadvantages to raising errors instead of having code fail silently in production?
  • This has been touched on on SO as far as implementations, but have server-logging JS errors an effective strategy?
  • Anything else I ought to know, regarding trapping errors in my application?

I'm also completely game for hearing of books that have great chapters or in-depth explanations of error-handling. Eloquent JavaScript touches on the matter, but isn't very prescriptive or opinionated about the issue.

Thanks for any advice you can give!

An immensely interesting set of slides on Enterprise JavaScript Error Handling can be found at http://www.devhands.com/2008/10/javascript-error-handling-and-general-best-practices/

In short it summarizes:

  1. Assume your code will fail
  2. Log errors to the server
  3. You, not the browser, handle errors
  4. Identify where errors might occur
  5. Throw your own errors
  6. Distinguish fatal versus non-fatal errors
  7. Provide a debug mode

The slides go into much more detail and most probably will give you some direction.


The presentation mentioned above can be found here: http://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation

Node.js Error Handling Best Practices: Ship With Confidence, To execute multiple statements, group them within a block statement ( { … } ). Best practice. In general, it's good practice to always use block� Always add some context to the errors (the version, the id of the object, some custom message, ) and also make sure you make a distinction between external errors (some external data or circumstance made your system fail) and internal errors/assertions (your own system messed up), read about 'Design by contract'.

Nicholas Zakas of Yahoo! fame did a talk on Enterprise Error Handling (slides) at Ajax Experience 2008, in which he proposed something like this:

function log(sev,msg) {
    var img = new Image();
    img.src = "log.php?sev=" +
        encodeURIComponent(sev) +
        "&msg=" + encodeURIComponent(msg);

// usage
log(1, "Something bad happened.")

// Auto-log uncaught JS errors
window.onerror = function(msg, url, line) {
    log(1, msg);
    return true;

A year later, Nicholas Zakas posted an update on his blog which included a clever pattern to inject error handling code automatically on your production environment (using aspect-oriented programming).

When you start logging window.error calls, you're going to notice two things:

  1. If your site is fairly complex, you're going to log a lot of errors
  2. You'll be seeing a bunch of useless "window.error in undefined:0" messages

Reducing the torrent of log entries is as simple as testing for severity and/or a random number before logging to the server:

function log(sev,msg) {
    if (Math.random() > 0.1) return; // only log some errors

    var img = new Image();
    img.src = "log.php?sev=" +
        encodeURIComponent(sev) +
        "&msg=" + encodeURIComponent(msg);

Handling the useless "window.error in undefined:0" errors depends on your site architecture, but can try identifying all Ajax calls and throwing an exception when something fails (possibly returning a stack trace using stacktrace.js).

Control flow and error handling, Best Practices for Handling Errors. One common criticism of JavaScript is the way errors are handled through callbacks. Check out the pattern� One of the most common methods for error handling is using the try-catch-finally block. Code in the try block will run first. catch will handle any exceptions that are thrown in the try block. finally is optional – This will run after try-catch regardless if an error has occurred.

Proper Error Handling in JavaScript ― Scotch.io, Developers working with Node.js sometimes find themselves writing not-so-clean code while handling all sorts of errors. This article will introduce you to� I’ve got some good news and some bad news. If you’re handling errors as best you can in your application, awesome! That’s the good news. The bad news is that you’re only halfway there. What do I mean? Well, handling errors in your program deals only with the things you know about.

Best Practices for Node.js Error-handling, I wanted to know the best practices around when we should throw an error, when we should use return , and when console.error should come� Best practice: When logging errors to the console inside a catch block, using console.error () rather than console.log () is advised for debugging. It formats the message as an error, and adds it to the list of error messages generated by the page.

Error Handling in JavaScript: a Quick Guide | by Bret Cameron, In this column, I discuss why, how, and when you should make use of JavaScript's try catch statement as well as throwing your own custom errors. Answers: In addition to the other answers: one important thing is to use context data available in JavaScript error objects and in the window.onerror function parameters. Things like the stacktrace (errorObject.stack), the filename, the line number and the column number. Note that each browser has some differences…so do your best effort to get nice errors.

Best Practices for Using JavaScrpt Try Catch Statements, Errors are good — I'm sure you've heard that before. At first sight we fear Errors, I. JavaScript Errors and generic handling. throw new� JavaScript. Errors - Throw and Try to Catch. Previous Next . The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. The finally statement lets you execute code, after try and catch, regardless of the result.

Handling Errors in JavaScript: The Definitive Guide, pow can handle it). In situations where it is not entirely clear what kind of input a function accepts, it is often a good idea to explicitly state the kind of arguments that�

  • It surely depends on how spectacularly you fail if something goes wrong and the volume of possible error messages. You do not want to fail because your error logging directory is full now do you? - Did you look here at all? stackoverflow.com/search?q=error+logging+javascript
  • @mplungjan - I did scan through the answers there, but not a lot seemed canonical, and searches for Javascript error handling/exception best practices turned up nothing, so I thought it could be helpful to try and solicit some condensed thoughts, both for my own understanding and future searchers. Perhaps this is a topic where prescribing best practices isn't as possible, but each situation is highly unique?
  • "Should every piece of code be wrapped in a try/catch?" Of course not. There's lots of code that you know will always work (assuming you test it, of course, but the point of try/catch is not to catch or gloss over coding errors). Only wrap code that might fail some of the time due to something outside its control, generally things like resource access, etc. Note: some things that can fail have built-in error handling, e.g., I would not bother coding Ajax from scratch when there are plenty of libraries that do it which handle cross-browser issues and let you specify an error handler function.
  • This is a good question Josh, +1. Lot's of syntactic advice around, but like you say that's the easy part. It is touched on in this question's answer (stackoverflow.com/questions/2825427/…) where it's explained that Exceptions are not as commonly used in JS and reasons are given.
  • The devhands link is broken.
  • To those that read this in 2017, I'd argue that you will not get much value from the slides - this summary gives you 90% of the information. It is still valuable information. Cheers!
  • I know this is an old question, but suggesting to randomly ignore some errors is one of the worst ideas I've ever heard.
  • @jbabey: For a small site you are right, but if you are running a large site with 100,000s or millions of users, you really don't need to flood your servers (or the internet) with redundant logging requests. On a large enough system, every real error is going to occur tens of thousands of times a day, so this form of limiting works just fine. The idea is actually implemented at Facebook.
  • Logging errors while in debugging mode is likely just as important as limiting production error reports, so one may note that a solution is needed for managing that value limiting the logging threshold.
  • @NickBull I reverse engineered a bunch of Facebooks JavaScript modules back in 2011-2012; that's where I found it.
  • @NickBull just checked my old files, still had these. I found this trick in the Facebook bootloader module: if (global.logJSError) if (Math.random() < .01) logJSError('bootloader', { (admittedly that code doesn't throttle all errors, only a specific class of timeout errors)
  • "The part of the code you want to wrap is a key part of the whole algorithm" - might depend on how you want to handle the failure. If you know there is no way to continue with the algorithm upon failure it might be better to wrap the whole thing in a try/catch because if your try/catch is (e.g.) buried inside nested loops it will be more of a performance hit. On the other hand if you can take some action on exception and continue with the algorithm then you will need a more fine-grained try/catch setup.