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"

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

--

--

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