npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

error-lib

v2.0.1

Published

Standard Error Library for JavaScript/TypeScript projects (NodeJS & Browsers)

Downloads

1,087

Readme

error-lib

NPM version NPM downloads Build Status

About

The error-lib project helps developers having a unified error structure in their NodeJS/Browser (JavaScript/TypeScript) projects.

Installation

To install this package, run the command below.

# npm
npm install error-lib
# yarn
yarn add error-lib
# pnpm
pnpm add error-lib

Diagram

error-lib diagram

Usage

To use any of the custom error libraries you need to simply import them in your typescript/javascript application.

// for NodeJS applications (Common JS)
const {
  ApplicationError,
  NotFoundError,
  ForbiddenError,
} = require('error-lib');

// Let's suppose we have a snippet that reads the content of a file
// 1) The first step is to check if the file exists.
// 2) The second step is to check if current user has access to the file.

const checkIfFileExist = (path) => {
  // 'fs.exists' is a pseudo code
  if (fs.exists(path) === false) {
    throw new NotFoundError(`${path} was not found.`);
  }

  return true;
};

const readFileContent = (path) => {
  if (fs.hasAccess(path) === false) {
    throw new ForbiddenError(`User does not have access to '${path}'`);
  }

  return 'dummy content';
};

try {
  // step 1
  checkIfFileExist('/path/to/file');

  // step 2
  const fileContent = readFileContent('/path/to/file');
} catch (err) {
  if (err instanceof NotFoundError) {
    // now you have intellisense enabled
    console.error('File not found!');
  } else if (err instanceof ForbiddenError) {
    // now you have intellisense enabled
    console.error('No access to the file');
  } else {
    console.error('Something went wrong!');
  }
}
// For typescript/javascript (ES Module)
import { ApplicationError, NotFoundError } from 'error-lib';

// Let's suppose we have a snippet that reads the content of a file
// 1) The first step is to check if the file exists.
// 2) The second step is to check if current user has access to the file.

const checkIfFileExist = (path) => {
  // 'fs.exists' is a pseudo code
  if (fs.exists(path) === false) {
    throw new NotFoundError(`${path} was not found.`);
  }

  return true;
};

const readFileContent = (path) => {
  if (fs.hasAccess(path) === false) {
    throw new ForbiddenError(`User does not have access to '${path}'`);
  }

  return 'dummy content';
};

try {
  // step 1
  checkIfFileExist('/path/to/file');

  // step 2
  const fileContent = readFileContent('/path/to/file');
} catch (err) {
  if (err instanceof NotFoundError) {
    // now you have intellisense enabled
    console.error('File not found!');
  } else if (err instanceof ForbiddenError) {
    // now you have intellisense enabled
    console.error('No access to the file');
  } else {
    console.error('Something went wrong!');
  }
}

Extend / Custom errors

Not the errors created in this package supports all the scenarios. It's not even possible 😁.

To add a new type of error that suits your needs, follow the instruction below.

It's always a good idea to extend errors from one of the main error types in this package. Unless you have your own reasons not to do so 😁.

// Let's suppose you're adding an InvalidUsernamePassword error (which can be derived from BadRequestError).

// invalid_username_password_error.ts
const { BadRequestError } = require('error-lib');

class InvalidUsernamePassword extends BadRequestError {
  /**
   *
   * @param message {string} Custom error message
   * @param opts Extra options
   */
  constructor(message, opts) {
    message = message ?? 'InvalidUsernamePasswordError';

    super(message, {
      cause: opts?.cause,
      code: opts?.code ?? 'E_INVALID_USERNAME_PASSWORD',
    });

    Error.captureStackTrace(this, InvalidUsernamePassword);
    Object.setPrototypeOf(this, InvalidUsernamePassword.prototype);
  }
}

module.exports = {
  InvalidUsernamePassword,
};

// in your application (e.g. app.js)
// Now you can use your new error class to throw more specific errors

if (user !== 'user1' && pass !== 'p4$sw0rd!') {
  throw new InvalidUsernamePassword();
}
// Let's suppose you're adding an InvalidUsernamePassword error (which can be derived from BadRequestError).

// invalid_username_password_error.ts

import { BadRequestError, BadRequestErrorConstructorOptions } from 'error-lib';

export interface InvalidUsernamePasswordConstructorOptions<
  TCauseError extends Error = Error,
> extends BadRequestErrorConstructorOptions<TCauseError> {}

export class InvalidUsernamePassword<
  TCause extends Error = Error,
> extends BadRequestError<TCause> {
  /**
   *
   * @param message Custom error message
   * @param opts Extra options
   */
  constructor(
    message?: string,
    opts?: InvalidUsernamePasswordConstructorOptions<TCause>,
  ) {
    message = message ?? 'InvalidUsernamePasswordError';

    super(message, {
      cause: opts?.cause,
      code: opts?.code ?? 'E_INVALID_USERNAME_PASSWORD',
    });

    Error.captureStackTrace(this, InvalidUsernamePassword);
    Object.setPrototypeOf(this, InvalidUsernamePassword.prototype);
  }
}

// in your application (e.g. app.ts)
// Now you can use your new error class to throw more specific errors

if (user !== 'user1' && pass !== 'p4$sw0rd!') {
  throw new InvalidUsernamePassword();
}

And you're good to go!

License

MIT