bugsy
TypeScript icon, indicating that this package has built-in type declarations

3.0.0-alpha.0 • Public • Published

bugsy

This library is meant to help to deal with errors lifecycle in JavaScript.

Error handling is a very common problem in every product. However, the language does not provide enough utils to deal with error management.

The work done in this library is inspired by personal experience while implementing more complex JavaScript projects and some other libraries such as verror.

build status npm version

Key Aspects

  • Universal module: This library can be used both in Node.js and in browsers.
  • Type first: Besides having a lot of runtime checks, the library is build to be used with type-safe extensions such as Typescript. The NPM package contains directly the Typescript definitions based on the sources.
  • Cause chain: While handling errors, even they might be expected, it is not always possible to recover into a proper state. In such cases, errors should be rethrown and the caller can try to handle the situation. In such cases, it might be useful to gather some metadata and keep track of previous errors.
  • Severity: When errors should be logged into third-party systems, not all errors have the same severity. This allows being informed only when the system is about to crash rather than on every simple network error that might occur.

Installation

$ npm install bugsy

Usage

import * as bugsy from 'bugsy';
 
const RAN_AWAY = 'RanAwayError';
const THROW_MISSED = 'ThrowMissedError';
const CAPTURE = 'CaptureError';
 
function capture(name) {
  const r = Math.random();
  if (< 0.3) {
    throw new bugsy.Bugsy({
      name: THROW_MISSED,
      message: 'Throw totally missed',
    });
  }
  if (< 0.6) {
    throw new bugsy.Bugsy({
      name: RAN_AWAY,
      message: `${name} ran away, again`,
      metadata: {
        direction: 'north',
      },
    });
  }
  throw new Error();
}
 
function handler(func) {
  try {
    func();
  } catch (error) {
    console.error(bugsy.getFullStack(error));
  }
}
 
handler(() => {
  while (true) {
    try {
      capture('Abra');
    } catch (error) {
      switch (true) {
        // Expected error
        case error.name === THROW_MISSED: {
          console.log('I can try again...');
          break;
        }
        // Expected error
        case error.name === RAN_AWAY: {
          const { direction } = bugsy.getMetadata(error);
          console.log(`Oh well... I should head ${direction}`);
          return;
        }
        // Unexpected error
        default:
          throw new bugsy.Bugsy({
            name: CAPTURE,
            message: 'Capture failed',
            cause: error,
            severity: 1,
          });
      }
    }
  }
});

License

MIT

Package Sidebar

Install

npm i bugsy

Weekly Downloads

3

Version

3.0.0-alpha.0

License

MIT

Unpacked Size

24 kB

Total Files

8

Last publish

Collaborators

  • njakob