Socket
Socket
Sign inDemoInstall

babel-plugin-transform-fake-error-class

Package Overview
Dependencies
53
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    babel-plugin-transform-fake-error-class

Transform error classes into error-returning functions


Version published
Maintainers
1
Install size
31.2 kB
Created

Readme

Source

babel-plugin-transform-fake-error-class

If you want to create your own error types, extending Error is the best way to do that:

class MyError extends Error {
  constructor(message) {
    super(message)
    this.name = 'MyError'
  }
}

Unfortunately, this doesn't work in old ES5 environments, and Babel's built-in class transforms don't always give good stack traces.

Since extending the built-in Error object doesn't always work, this plugin doesn't do that. Instead, it transforms the above class into something like this:

function MyError(message) {
  var _this = new Error(message)
  _this.name = 'MyError'
  return _this
}

This works almost perfectly in both old and new environments. You still call new MyError(), just as before, properties like name appear as they should, and stack traces look perfect, but under the hood this is no longer a class. That means instanceof MyError will always return false, but that's the only major downside.

This plugin also supports methods and class properties, including static ones:

class MyError extends Error {
  name = 'MyError'

  static isMyError(error) {
    return error.constructor === MyError
  }

  getReason() {
    return this.message
  }
}

Installing

npm install --save-dev babel-plugin-transform-fake-error-class
# or
yarn add --dev babel-plugin-transform-fake-error-class

Now add this plugin to your .babelrc:

{
  "plugins": [
    "babel-plugin-transform-fake-error-class"
  ]
}

FAQs

Last updated on 22 Jul 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc