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

named-app-errors

v4.0.2

Published

A handy set of NAMED (i.e. in the stack trace) error classes with deep TypeScript support and other useful additions

Downloads

109

Readme

npm version

named-app-errors

This package exports a set of "named" (i.e. in the stack trace) typed error classes extending the Error class. The output of these errors provides better DX than is achieved by extending Error alone, especially when using minifiers.

This package includes TypeScript types and provides:

  • A UMD/CJS/AMD bundle (no tree-shaking)
  • ES2015 modules (tree-shaking)

Install

npm install named-app-errors

Usage

When creating your own error classes, you should extend AppError (or any of its descendants) and call the special makeNamedError method afterwards like so:

import { AppError, makeNamedError } from 'named-app-errors';

export class CustomSpecialError extends AppError {
    constructor(message?: string) {
        super(message ?? 'something important failed');
    }
}
makeNamedError(CustomSpecialError, 'CustomSpecialError');

export class DeepCustomSpecialError extends CustomSpecialError {
    constructor(details?: string)
    constructor(
      public readonly details = '(no details)',
      message: string | undefined = undefined
    ) {
        super(message ?? `something important failed: ${details}`);
    }
}
makeNamedError(DeepCustomSpecialError, 'DeepCustomSpecialError');

It might seem redundant to supply both the class object and a class name string, but it is necessary for the shiny new error name to survive minification.

Note how DeepCustomSpecialError's parameter list ends with message: string | undefined = undefined. Ensuring your error constructor always accepts an optional message as its final parameter allows easy extension of all AppError subclasses. Additionally, the public readonly parameter property can be used to expose any extra constructor arguments.

Afterwards, you can use your error classes like so:

import { AppError } from 'named-app-errors';
// ...
try {
  // ...
  if (badness) {
    throw new CustomSpecialError();
  }
  // ...
  if (badCondition) {
    throw new DeepCustomSpecialError('bad bad not good');
  }
} catch (e) {
  if (e instanceof DeepCustomSpecialError) {
    console.warn(e.details);
    externalLogger(e);
  } else if (e instanceof AppError) { // ◄ Catches any other AppError subtypes
    console.error(e);
  } else {
    // Must be someone else's problem
    throw e;
  }
}

Type Glossary

This library comes with the following error types built in:

AppError

AppError(message?: string) extends Error

AppError represents a generic application error. It should be used as an application-wide base error class, which makes hygienic practices like application-specific instanceof guards in catch blocks much easier to implement and more meaningful in context.

Example

import { AppError } from 'named-app-errors';

throw new AppError('badness');

AuthError

AuthError(message?: string) extends AppError

AuthError represents a generic auth error.

Example

import { AuthError } from 'named-app-errors';

throw new AuthError();

NotAuthenticatedError

NotAuthenticatedError(message?: string) extends AuthError

NotAuthenticatedError represents an authentication failure.

Example

import { NotAuthenticatedError } from 'named-app-errors';

throw new NotAuthenticatedError();

NotAuthorizedError

NotAuthorizedError(message?: string) extends AuthError

NotAuthorizedError represents an authorization failure.

Example

import { NotAuthorizedError } from 'named-app-errors';

throw new NotAuthorizedError();

GuruMeditationError

GuruMeditationError(message?: string) extends AppError

GuruMeditationError represents the occurrence of a supposedly impossible runtime condition, the implication being the assistance of a senior developer is required to debug efficiently. Scary!

Example

import { GuruMeditationError } from 'named-app-errors';

throw new GuruMeditationError();

HttpError

HttpError(
  public readonly res?: ServerResponseLike,
  error?: string
) extends AppError

HttpError represents a generic HTTP, request, response, or related failure.

The ServerResponseLike type is compatible with response types from Node.js and most fetch libraries:

type ResponseShapeA = { statusCode: number; statusMessage: string };
type ResponseShapeB = { status: number; statusText: string };
type ServerResponseLike = ResponseShapeA | ResponseShapeB;

Example

import { HttpError } from 'named-app-errors';
import { fetch } from 'node-fetch';

try {
  const res = await fetch('https://some.url');

  if (!res.ok) {
    throw new HttpError(res);
  }
  // ...
  if(...) {
    throw new HttpError(res, 'some specific error occurred');
  }
} catch (e) {
  if (e instanceof HttpError) {
    console.log('extra context:', e.res.headers.raw());
  }

  handleError(e);
}

NotFoundError

NotFoundError(message?: string) extends AppError

NotFoundError represents a failure to locate something.

Example

import { NotFoundError } from 'named-app-errors';

throw new NotFoundError('user');

ItemNotFoundError

ItemNotFoundError<T = undefined>(
  public readonly item?: T,
  public readonly itemName?: string
) extends NotFoundError

ItemNotFoundError represents the failure to locate a specific item.

Example

import { ItemNotFoundError } from 'named-app-errors';
import { ObjectId } from 'mongodb';

const ref = 'some-string-reference-id';
const id = new ObjectId(ref);
// ...
throw new ItemNotFoundError();
throw new ItemNotFoundError(id);
throw new ItemNotFoundError(ref);

TrialError

TrialError(message?: string) extends AppError

TrialError represents a generic failure that occurred while setting up and/or running a test. This error should never appear outside of a testing environment.

Example

import { TrialError } from 'named-app-errors';

jest.beforeAll(() => {
  throw new TrialError('failed to setup test environment');
});

DummyError

DummyError(message?: string) extends TrialError

DummyError is a generic pseudo-error meant to be thrown, caught, and consumed exclusively within a testing environment to verify the correctness of error handling behavior.

Example

import { DummyError } from 'named-app-errors';
import { thingUnderTest } from './place';

it('handles errors properly', async () => {
  await expect(thingUnderTest(() => {
    throw new DummyError('this error should be caught');
  })).resolves.toBeUndefined();
});

ValidationError

ValidationError(message?: string) extends AppError

ValidationError represents a generic validation failure.

Example

import { ValidationError } from 'named-app-errors';

throw new ValidationError('invalid data received');

AppValidationError

AppValidationError(message?: string) extends ValidationError

AppValidationError represents a generic validation failure outside of the user's control.

Example

import { AppValidationError } from 'named-app-errors';

throw new AppValidationError('invalid application data');

InvalidAppConfigurationError

InvalidAppConfigurationError(
  public readonly details?: string
) extends AppValidationError

InvalidAppConfigurationError represents an application misconfiguration outside of the user's control.

Example

import { InvalidAppConfigurationError } from 'named-app-errors';

throw new InvalidAppConfigurationError('config at "./myapp.config.js" is invalid');

InvalidAppEnvironmentError

InvalidAppEnvironmentError(
  public readonly details?: string
) extends AppValidationError

InvalidAppEnvironmentError represents a misconfigured runtime environment outside of the user's control.

Example

import { InvalidAppEnvironmentError } from 'named-app-errors';

throw new InvalidAppEnvironmentError('missing NODE_ENV in process.env');

ClientValidationError

ClientValidationError(message?: string) extends ValidationError

ClientValidationError represents a generic validation failure due to user error.

Example

import { ClientValidationError } from 'named-app-errors';

throw new ClientValidationError('invalid data received');

InvalidClientConfigurationError

InvalidClientConfigurationError(
  public readonly details?: string
) extends ClientValidationError

InvalidClientConfigurationError represents a user-provided misconfiguration.

Example

import { InvalidClientConfigurationError } from 'named-app-errors';

throw new InvalidClientConfigurationError('client config is invalid');

InvalidItemError

InvalidItemError<T = undefined>(
  public readonly item?: T,
  public readonly itemName?: string = 'id'
) extends ClientValidationError

InvalidItemError represents encountering a specific invalid item.

Example

import { InvalidItemError } from 'named-app-errors';
import { ObjectId } from 'mongodb';

const ref = 'some-ref-string';
let oid: ObjectId;

try {
  oid = new ObjectId(ref);
} catch {
  throw new InvalidItemError(ref);
}

InvalidSecretError

InvalidSecretError(secretType?: string) extends ClientValidationError

InvalidSecretError represents a failure while validating credentials, key material, some token, or other sensitive data. This error does not reveal any additional information about the data or the error other than that it occurred.

import { InvalidSecretError } from 'named-app-errors';

const secret = ...
const token = new BearerToken(secret);

if(!token) {
  throw new InvalidSecretError();
  // Or:
  throw new InvalidSecretError('bearer token');
}