Git Product home page Git Product logo

fejl's Introduction

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): T

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

fejl's People

Contributors

jeffijoe avatar dependabot[bot] avatar saghen avatar johannesschobel avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.