Custom JavaScript Errors in ES6

Why Do We Care About Error Objects?

throw "this is not an error"
test.js:1
(function (exports, require, module, __filename, __dirname) { throw "this is not an error"
^
this is not an error
throw new Error("this is not an error")
test.js:1
(function (exports, require, module, __filename, __dirname) { throw new Error("this is not an error")
^

Error: this is not an error
at Object.<anonymous> (test.js:1:69)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js

Why Bother with Custom Errors?

var error = new Error("Could not access the file")
error.code = "EACCES"
  1. It can be a lot of lines of code (1 line per extra property)
  2. Your error instance can’t have any custom methods

How Do We Make Custom Errors?

class MyError extends Error {}
Error: there was a problem
at GoodError (custom-errors.js:1:63)
at getError (custom-errors.js:4:25)
at Object.<anonymous (custom-errors.js:7:1)
Error: there was a problem
at getError (fancy-errors.js:9:5)
at Object.<anonymous> (fancy-errors.js:12:1)

Tl;dr

  1. Always use error objects instead of strings to preserve a stack trace
  2. Appending common properties to errors is used by node.js to provide additional context
  3. Custom error objects allow for adding your own methods and make capturing additional metadata into your errors a lot of easier
  4. class MyError extends Error {} is basically good enough
  5. Override the constructor and use Error.captureStackTrace if you want to streamline the stack trace a bit.

--

--

--

UI Engineering Leader

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jamund Ferguson

Jamund Ferguson

UI Engineering Leader

More from Medium

Asynchronous JavaScript

S.O.L.I.D and JavaScript

Principles of Application Frameworks and JavaScript

Hoisting in Javascript