Thanks to visit codestin.com
Credit goes to github.com

Skip to content
/ betterr Public

A better way to handle errors. Both data and errors are declared with const, available at the top level, and non-nullable (once the other is handled). Errors are always Error objects.

License

Notifications You must be signed in to change notification settings

syhner/betterr

Repository files navigation

betterr

A better way to handle errors

build status coverage vulnerabilities

Advantages

  • File structure remains flat, unlike with nested try...catch
  • Both data and errors are declared with const, unlike with non-nested try...catch
  • Both data and errors are non-nullable, once an early return occurs if the other is null
  • Both data and errors are available at the top level, unlike with try...catch or promises
  • Work with errors that are always Error objects by default, without compromising type-safety, unlike with try...catch or promises
  • TypeScript support with optional generic parameters for data and error types

Installation

$ npm install betterr

Usage

import { betterr, betterrSync } from 'betterr';
// const { betterr, betterrSync } = require('betterr');

const { data: user, err } = await betterr(() => getRandomUser());
//            ^?    ^? user: User | null, err: Error | null

if (err) {
  // ^? err: Error
  return;
}

return user;
//     ^? user: User
  • betterr can be used with both asynchronous and synchronous callbacks
  • betterrSync can only be used with synchronous callbacks, but avoids wrapping the data in a promise, so await is not necessary

TypeScript

Both betterr and betterrSync are generic, so the type of data and error can be provided. The callback return type must be assignable to the first generic parameter (for data).

/**
 * const betterrSync: <TData, TError = Error>(callback: () => TData) =>
 * | { data: TData; err: null }
 * | { data: null; err: TError }
 */

const { data, err } = betterrSync<User, MyError>(() => ({
  //    ^?    ^? data: User | null, err: MyError | null
  userId: 1,
}));

About

A better way to handle errors. Both data and errors are declared with const, available at the top level, and non-nullable (once the other is handled). Errors are always Error objects.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •