All Projects → jeffijoe → fejl

jeffijoe / fejl

Licence: MIT license
Error-making utility for Node apps.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to fejl

react-loading-icons
A TypeScript-React edition of Sam Herbert's amazing SVG Loaders.
Stars: ✭ 32 (+6.67%)
Mutual labels:  typescript-library
superagent-intercept
Add functions that will be called during end() e.g. for handling error conditions without having the same code all over the place.
Stars: ✭ 23 (-23.33%)
Mutual labels:  error-handling
safe-touch
⛓ Runtime optional chaining for JS
Stars: ✭ 71 (+136.67%)
Mutual labels:  typescript-library
custom-exception-middleware
Middleware to catch custom or accidental exceptions
Stars: ✭ 30 (+0%)
Mutual labels:  error-handling
jsonrpc-ts
A very flexible library for building JSON-RPC 2.0 endpoints
Stars: ✭ 19 (-36.67%)
Mutual labels:  typescript-library
failure
Error management
Stars: ✭ 1,448 (+4726.67%)
Mutual labels:  error-handling
babel-errors
Nicer error messages for Babel
Stars: ✭ 15 (-50%)
Mutual labels:  error-handling
miette
Fancy upgrade to std::error::Error.
Stars: ✭ 945 (+3050%)
Mutual labels:  error-handling
result17
A rust like Result type for modern C++
Stars: ✭ 13 (-56.67%)
Mutual labels:  error-handling
failure
An error handling package for Go.
Stars: ✭ 24 (-20%)
Mutual labels:  error-handling
TypeScript-Library-Checklist
Your pre-launch checklist.
Stars: ✭ 19 (-36.67%)
Mutual labels:  typescript-library
bugsnag
Report errors with Bugsnag 🐛
Stars: ✭ 37 (+23.33%)
Mutual labels:  error-handling
sqlweb
SqlWeb is an extension of JsStore which allows to use sql query for performing database operation in IndexedDB.
Stars: ✭ 38 (+26.67%)
Mutual labels:  typescript-library
retryx
Promise-based retry workflow library.
Stars: ✭ 21 (-30%)
Mutual labels:  error-handling
progress-bar-log
A component to display a progress bar and last X logs at the same time.
Stars: ✭ 44 (+46.67%)
Mutual labels:  error-handling
constant-time-js
Constant-time JavaScript functions
Stars: ✭ 43 (+43.33%)
Mutual labels:  typescript-library
react-error-guard
⚛️An overlay for displaying stack frames based on create-react-app/packages/react-error-overlay
Stars: ✭ 18 (-40%)
Mutual labels:  error-handling
karkas
A tiny template engine based on TypeScript
Stars: ✭ 14 (-53.33%)
Mutual labels:  typescript-library
tzientist
Scientist-like library for Node.js in TypeScript
Stars: ✭ 37 (+23.33%)
Mutual labels:  typescript-library
react-picture-annotation
A simple annotation component.
Stars: ✭ 53 (+76.67%)
Mutual labels:  typescript-library

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].