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

fejl's People

Contributors

dependabot[bot] avatar jeffijoe avatar johannesschobel avatar saghen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

fejl's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

ErrorBag and BaseError

Dear @jeffijoe ,

thanks a lot for this awesome package. I toyed a bit around, and i quite liked it!
However, i came across the following use-case i would like to discuss with you.

I would like to introduce some kind of ErrorBags , where i can add errors. Consider, for example, the following situation: The api consumer submits data and the API answers with a lot of exceptions, based on the errors the user made. For example:

{
  status: 400,
  errors: [
    {
      type: "BadRequest",
      message: "E-Mail not properly formatted",
      status: 400,
      meta: {
        timestamp: 1234567890,
        url: "some/url/here",
      },
      attribute: "user.email"
    },
    {
      // another error here
    },
    {
      // and another error here
    }
  ]
}

It would be benefitial to define the class as follows:

export class ErrorBag {
  errors: BaseError[];
}

however, the BaseError must be properly typed because it is generic. How can i solve this issue? Am i missing something? I most likely cannot add the typing in the ErrorBag itself, as the ErrorBag may contain different errors (e.g, validation errors, authentication errors and whatever-other-type of errors)..

All the best and thanks a lot for your time / help!

PS: Would it be good to add this to the package as well? What do you think?

Set Custom Properties in assert()

Dear @jeffijoe ,
this package looks really nice - i like the approach of proving assert() methods! When browsing through the code, i thought, that it may be useful to allow overriding (or even setting) specific properties within the assert() methods...

function updateUser(user) {
  ValidationException.assert(user.name, 'Username is required', { url: 'https://my-fancy-endpoint/api/user/4711', method: 'POST', param: 'username' })
}

What do you think? Would it be benefitial to add this additional parameter?
All the best

Native ESM Support

Currently when using ESM in Node, imports have to be done like so.

import fejl from "fejl";
const { NotImplemented } = fejl

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.