arshia-gh / literal-error

Create strongly typed errors with ease

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

literal-error

Create strongly typed errors with ease

Documentation

Although not necessary, before using literal-error we strongly suggest you to convert your errors to constant objects as demonstrated in below code:

const NotAllowed = {
  name: 'NotAllowed'
  message: 'You are not allowed to perform this action'
  action: 'write:users'
} as const

Start with wrapping your function definition with throws and pass any error that might be thrown from this function

import { throws } from 'literal-error'

const writeUser = () => {
  /// implementation
}

const unsafeWriteUser = throws(writeUser, NotAllowed)

You can call the unsafe function by using Try function as demonstrated in below code:

import { Try } from 'literal-error'

const result = Try(
  unsafeWriteUser(),
)

However the previous code will result in a compile error as previously marked error is not handled, to handle errors you can use the 'Catch' function to catch and handle any possible errors as such:

const result = Try(
  unsafeWriteUser(),
  Catch(NotAllowed, () => {
    /// implementation
  },
) // result is either the return value of your function or catch handle function

About

Create strongly typed errors with ease

License:MIT License


Languages

Language:TypeScript 98.2%Language:JavaScript 1.3%Language:Shell 0.6%