Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

babel-plugin-transform-fake-error-class

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-plugin-transform-fake-error-class

Transform error classes into error-returning functions

  • 1.0.0
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
9
decreased by-90.62%
Maintainers
1
Weekly downloads
 
Created
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

Package last updated on 22 Jul 2020

Did you know?

Socket

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc