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

fejl

v3.0.1

Published

Error-making utility for JavaScript apps.

Downloads

5,367

Readme

Fejl

Error utility for Node apps, written in TypeScript.

npm dependency Status devDependency Status Build Status Coveralls npm npm Built with TypeScript

Install

With npm:

npm install fejl

Or with yarn

yarn add fejl

Usage

Fejl exports a general-purpose MakeErrorClass function which lets you build an error class with a default message and attributes.

import { MakeErrorClass } from 'fejl'

class InvalidConfigError extends MakeErrorClass(
  // Default message
  'The configuration file is invalid',
  // Default props
  { infoUrl: 'https://example.com/error-info' }
) {}

// Using defaults
try {
  throw new InvalidConfigError()
} catch (err) {
  console.log(err.name) // 'InvalidConfigError'
  console.log(err.message) // 'The configuration file is invalid'
  console.log(err.infoUrl) // 'https://example.com/error-info'
  console.log(err.stack) // <error stack>
  console.log(err instanceof InvalidConfigErrror) // true
}

// Overriding defaults
try {
  throw new InvalidConfigError('The config file was not found', {
    infoUrl: 'https://example.com/other-err',
    code: 123
  })
} catch (err) {
  console.log(err.message) // 'The configuration file is invalid'
  console.log(err.infoUrl) // 'https://example.com/other-err'
  console.log(err.code) // 123
}

Additionally, for your convenience, a few common HTTP errors have been defined which set a statusCode, see http.ts for which ones. If you think I missed some important ones, feel free to open an issue/PR.

Additional awesomeness

Fejl wants to get rid of excessive boilerplate in conditionally throwing errors. Therefore, each error class created with MakeErrorClass comes with the following static functions:

assert<T>(data: T, message: string): void

Let's create ourselves an error class to play with.

import { MakeErrorClass } from 'fejl'

// Defaults are optional
class InvalidInput extends MakeErrorClass() {}

Let's see how InvalidInput.assert can make our lives easier.

Ugly:

function someFunc(value) {
  if (!value) {
    throw new InvalidInput('Value is required.')
  }
}

Sexy:

function someFunc(value) {
  InvalidInput.assert(value, 'Value is required')
}

makeAssert<T>(message: string): Asserter<T>

Sometimes an error can be thrown in multiple places, but the message would be the same. makeAssert will generate an asserter function that can be reused, and which is also really useful when working with Promises.

MyError.makeAssert('Nope') is essentially sugar for (data) => MyError.assert(data, 'Nope').

For this example, we want to use one of the built-in HTTP errors.

import { NotFound } from 'fejl'

Ugly:

async function getTaskForUser(userId, taskId) {
  const user = await getUserAsync(userId)
  if (!user) {
    throw new NotFound('User not found')
  }

  const task = await getTaskAsync(userId, taskId)
  if (!task) {
    throw new NotFound('Task not found')
  }

  return task
}

Sexy:

async function getTaskForUser(userId, taskId) {
  const user = await getUserAsync(userId)
  NotFound.assert(user, 'User not found')

  const task = await getTaskAsync(userId, taskId)
  NotFound.assert(task, 'Task not found')

  return task
}

Sexier:

async function getTaskForUser(userId, taskId) {
  const user = await getUserAsync(userId).then(
    NotFound.makeAssert('User not found')
  )

  const task = await getTaskAsync(userId, taskId).then(
    NotFound.makeAssert('Task not found')
  )

  return task
}

retry<T>(fn: () => Promise<T>, opts?: RetryOpts): Promise<T>

Keeps running the inner fn until it does not throw errors of the type that .retry was called on.

const eventuallyExists = await NotFound.retry(
  async () => {
    const report = await getSomeReportThatMayOrMayNotExistAtSomePointInTime().then(
      NotFound.makeAssert('The report was not found')
    )
    return report
  },
  {
    // These are available options with their defaults.
    tries: 10, // How many times to try
    factor: 2, // The exponential backoff factor to use.
    minTimeout: 1000, // The minimum amount of time to wait between retries in ms
    maxTimeout: Infinity // The nax amount of time to wait between retries in ms
  }
)

You can import the retry top-level utilty that is not bound to any particular error.

The API is similar to promise-retry.

import { retry } from 'fejl'

const result = await retry(
  async (again, attempt) => {
    return getSomeReportThatMayOrMayNotExistAtSomePointInTime()
      .then(NotFound.makeAssert('The report was not found'))
      .catch(err => {
        if (err instanceof NotFound) {
          // Only retry on NotFound errors.
          throw again(err)
        }
        throw err
      })
  },
  {
    // options...
    tries: 10
  }
)

ignore<T>(valueToReturnOnCatch: T): IgnoreFunc<T>

Makes an ignore function for this error class that will return the specified value if caught. Otherwise throws the original error.

// If a `NotFound` is thrown, returns 99.95
const price = await getSomeRemotePriceThatMayOrMayNotExist().catch(
  NotFound.ignore(99.95)
)

// Using try-catch
try {
  return getSomeRemotePriceThatMayOrMayNotExist()
} catch (err) {
  return NotFound.ignore(99.95)(err)
}

You can check multiple errors at once by using the top-level higher-order ignore utility.

import { ignore } from 'fejl'

// If a `NotFound` or `Forbidden` is thrown, returns 99.95
const price = await getSomeRemotePriceThatMayOrMayNotExist().catch(
  // Note the double-invocation
  ignore(NotFound, Forbidden)(99.95)
)

getHttpErrorConstructorForStatusCode(statusCode: number): HttpErrorConstructor

Given a status code, returns the proper error to throw.

import { getHttpErrorConstructorForStatusCode, BadRequest } from 'fejl'

const ErrorCtor = getHttpErrorConstructorForStatusCode(400)

ErrorCtor === BadRequest // true

What's in a name?

"fejl" [fɑjl] is danish for "error", and when pronounced in English also sounds like the word "fail".

Author

Jeff Hansen — @Jeffijoe