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

@kettil/errors

v1.1.0

Published

Simple creation of customized error classes.

Downloads

2

Readme

Custom Errors

npm

Simple creation of customized error classes.

Installation

npm install @kettil/errors

Usage

import { customAggregateError, customError } from '@kettil/errors';

// create a custom error
class SimpleExampleError extends customError({
  code: 'SimpleExample';
})

// throw the custom error
throw new SimpleExampleError('message');

// or for a custom aggregate error
class SimpleAggregateExampleError extends customAggregateError({
  code: 'SimpleAggregateExample';
})

throw new SimpleAggregateExampleError([/* error instances */])

Custome errors

A complete example with explanation of the parameters.

// Create a error class
class ExampleError extends customError({
  code: 'UniqueErrorCode',
  // statusCode is used in the context of an web API and is
  // interpreted by e.g. Fastify. [Default: 500]
  statusCode = 500, // optional
  // The error message if none was defined when throwing, if
  // "defaultMessage" is undefined, then the converted "code"
  // value is used. ("UniqueErrorCode" => "Unique error code.")
  defaultMessage: 'Error message.', // optional
  // Which keys are required in the data object, then when
  // throwing the error, an object must always be passed where
  // the object "data" has the defined keys.
  requiredDataKeys: ['key1'] as const, // optional
})

// The simplest kind. Error message is the default message.
// The call is only possible if "requiredDataKeys" is undefined.
throw new ExampleError();

// The natural kind. Overwrites the default message.
// The call is only possible if "requiredDataKeys" is undefined.
throw new ExampleError('Other error message.');

// The complete kind. All parameters are optional.
// If "requiredDataKeys" is defined, then "data" is required
throw new ExampleError({
  message: 'Error message.',
  // Error instance from a previous error.
  cause: otherErrorVariable,
  // Additional data relevant to the context of the error.
  // If "requiredDataKeys" is defined, then the object
  // must contain the defined keys.
  data: { foo: 42 },
});

A detailed description of "cause" can be found in the Mozilla MDN.

Custom aggregate errors

A complete example with explanation of the parameters.

// Create a error class
class ExampleAggregateError extends customAggregateError({
  code: 'UniqueErrorCode',
  // statusCode is used in the context of an web API and is
  // interpreted by e.g. Fastify. [Default: 500]
  statusCode = 500, // optional
  // The error message if none was defined when throwing, if
  // "defaultMessage" is undefined, then the converted "code"
  // value is used. ("UniqueErrorCode" => "Unique error code.")
  defaultMessage: 'Error message.', // optional
  // Which keys are required in the data object, then when
  // throwing the error, an object must always be passed where
  // the object "data" has the defined keys.
  requiredDataKeys: ['key1'] as const, // optional
})

// The simplest kind. An array with errors
// The call is only possible if "requiredDataKeys" is undefined.
throw new ExampleAggregateError([/* ... */]);

// The complete kind. All parameters except "errors" are optional.
// If "requiredDataKeys" is defined, then "data" is required
throw new ExampleAggregateError({
  errors: [/* ... */],
  message: 'Error message.',
  // Additional data relevant to the context of the error.
  // If "requiredDataKeys" is defined, then the object
  // must contain the defined keys.
  data: { foo: 42 },
});

Test functions

With the following test functions, it can be tested, whether a variable is an Error/CustomError/CustomAggregateError instance.

import { isCustomAggregateError, isCustomError, isError } from '@kettil/errors';

if (isError(errorVariable)) {
  // is true if the variable is an instance of
  // Error/AggregateError/CustomError/CustomAggregateError
}

if (isCustomError(errorVariable)) {
  // is true if the variable is an instance of CustomError
}

if (isCustomError(errorVariable, SimpleExampleError)) {
  // is true if the variable is an instance of CustomError
  // and "code" value is equal
}

if (isCustomAggregateError(errorVariable)) {
  // is true if the variable is an instance of CustomAggregateError
}

if (isCustomAggregateError(errorVariable, SimpleExampleError)) {
  // is true if the variable is an instance of CustomAggregateError
  // and "code" value is equal
}

Logger support

The CustomError/CustomAggregateError instances have a built-in toJSON() function so that a consistent output is generated when logging.

Example for a Project

Create an errors.ts in the lib folder of your project. In this file all error cases for this project are defined.

/* eslint-disable max-classes-per-file -- collect all error classes */
import { customAggregateError, customError, defaultErrors, defaultAggregateErrors } from '@kettil/errors';

// Custome errors

class SimpleExampleError extends customError({
  code: 'SimpleExample';
})

class FullExampleError extends customError({
  code: 'FullExample';
  statusCode: 404;
  defaultMessage: 'Default error message.';
})

// Custome aggregate errors

class FullAggregateExampleError extends customAggregateError({
  code: 'FullAggregateExample';
  statusCode: 404;
  defaultMessage: 'Default aggregate error message.';
})

// Object with all custom errors

const errors = {
  ...defaultErrors,
  ...defaultAggregateErrors,

  SimpleExampleError,
  FullExampleError
} as const;

export { errors };

If an error is to be thrown, the error classes can simply be imported.

import { errors } from '<path>/errors.ts';

// ...

throw new errors.FullExampleError();

// ...

Integrated customized error classes

| Error | Description | | -------------------------- | ---------------------------------------------- | | ExternalServiceError | A wrapper for an error of an external service. | | GenericError | Replaced the original error class. | | GenericAggregateError | Replaced the original aggregate error class. | | NotImplementedError | If a feature is not yet fully implemented. | | OutsideRangeError | If a value is out of the allowed range. | | UndefinedSwitchCaseError | If an undefined switch case occurs. | | WrongTypeError | If the variable has the wrong type. |