JavaScript: Creating Custom Error Classes That Work After Transpiling To ES5

Vit Gordon
Nov 11, 2017 · 1 min read

TL/DR: here’s a nice hack that we use in CCXT:

class MyError extends Error {   constructor (message) {      super (message)      this.constructor = MyError
this.__proto__ = MyError.prototype
this.message = message
}
}

The above is necessary in many popular frameworks. The popularcreate-react-app framework, for example, forces us to transpile everything down to ES5 when building for production. This is required by some outdated dependencies like Uglify, that don’t even recognize classes despite the broad adoption of ES6 in modern browsers…

…and the instanceof just stops working after that. Here’s a simple test:

// test.jsclass MyError extends Error {}
let myerr = new MyError ()
console.log (myerr instanceof MyError)

Guess what happens if you run it? It prints true, obviously. But after your code goes through Babel with ES5 preset enabled (in order to meet the popular frameworks’ requirements), the outcome isn’t true anymore:

babel test.js --out-file test.es5.js --presets=es2015
node test.es5.js

Will print false, which is quite unexpected… The problem described above can be easily solved by adding a hack shown in the beginning of this article.

Happy coding!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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