JS Coding – A Better Error Handler for JavaScript

My approach to JS tracing and logging is a fairly formalised token based log switching. But fundamentally it’s a console .log – so this does not have to be ground-breaking to be considered better !

I’m signed up for Chris Ferdinandi’s excellent daily developer tips email – go take a look at GoMakeThings.com if you’re interested in a daily tip and more broadly in Vanilla JS. The list of tips is at that link and you can sign up there too. One of his recent tips included a link to a video by Steve Griffith debugging beyond console.log() – see below.

The part I found interesting was the following.

window.addEventListener('error', messedUp);
function messedUp(err) {
  let msg = err.message;
  let line = err.lineno;
  let col = err.colno;
  let fn = err.filename;
  x = 789;
  console.error(msg, line, col, fn);

The cool affect here is that this gives you a custom error handler. No more must you rely on the mercy of the browsers red message. The addEventListener line should come somewhere early in the code – this tells JS to call the messedUp function when an error occurs, and crucially, before it generates its usual error output.

Inside the messedUp() function, the err.preventDefault() does what it says and stops the usual error message output. Then we get the error info and log it, but of course we could post it off to a server for analysis, show the user a pleasing modal alert, etc, which is the truly neat thing I had not previously considered.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: