Just a Quick Reminder to Always Handle Errors

May 2020

You should always handle errors. It's a lot harder to debug if you don't. And it's the sort of debugging that would be avoidable if you just weren't as lazy in the first place!

Here's an actual example that has happened to me while writing the code for blog:

// apply highlight
rehype()
  .use(highlight)
  .process(vfile.readSync(distLocation(page)), function (err, file) {
    fs.writeFileSync(distLocation(page), String(file));
  });
    

I thought: well, what could possibly happen here, I know this will always work. No need to handle the error.

Then, couple of weeks later I get the following problem: A file simply has the content "undefined". What happened here?! After a bit of debugging I found the culprit: Highlight.js didn't know the language "mysql" I tried to use, so it failed. But since I swalled the error I had no idea whatsoever where in my code something had gone wrong. Had I simply handled the error like this:

// apply highlight
rehype()
  .use(highlight)
  .process(vfile.readSync(distLocation(page)), function (err, file) {
    if (err) {
      console.error(err);
    } else {
      fs.writeFileSync(distLocation(page), String(file));
    }
  });
    

I could have saved myself a bit of trouble, since the following error message would have been printed:


Error: Unknown language: `mysql` is not registered
    at FormattedError (.../node_modules/fault/index.js:29:12)
    at coreHighlight (.../node_modules/lowlight/lib/core.js:195:11)
    at High.highlight (.../node_modules/lowlight/lib/core.js:112:20)
    at visitor (.../node_modules/rehype-highlight/index.js:71:27)
    at overload (.../node_modules/unist-util-visit/index.js:27:12)
    at one (.../node_modules/unist-util-visit-parents/index.js:34:25)
    at all (.../node_modules/unist-util-visit-parents/index.js:57:16)
    at one (.../node_modules/unist-util-visit-parents/index.js:42:28)
    at all (.../node_modules/unist-util-visit-parents/index.js:57:16)
    at one (.../node_modules/unist-util-visit-parents/index.js:42:28)
    

Still not perfect, but a lot better than getting nothing!

Interested in web development?


Learn to Write Clean Code

Clean Code: A Handbook of Agile Software Craftsmanship (Robert C. Martin)