You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

betterr

Package Overview
Dependencies
Maintainers
1
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

betterr

A better way to handle errors

6.0.0
latest
Source
npmnpm
Version published
Weekly downloads
5
-37.5%
Maintainers
1
Weekly downloads
 
Created
Source

betterr

A better way to handle errors

build status coverage

Advantages

Unlike with try...catch or promises:

  • 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

Installation

$ npm install betterr

Usage

  • Wrap any code that may throw
import { betterr } from 'betterr'; // const { betterr } = require('betterr');

const [user, err] = await betterr(() => getUserWithId(1));
// user: User | null, err: Error | null
  • Now either
  • Avoid handling the error, and use optional chaining

    const maybeName = user?.name; // maybeName: string | undefined
    
  • Handle the error (interrupting the control flow), after which optional chaining is not needed

    if (err) return; // user: User (after error handled)
    const name = user.name; // name: string
    

Explanation

betterr / betterSync execute a callback and return a tuple with data (callback return value) and err (error during execution), one of which will be null depending on the success of the callback.

  • 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 that await is not necessary.

TypeScript

Both betterr and betterrSync are generic.

  • The callback return type must be assignable to the first generic parameter (for data). It defaults to the callback return type.
  • The second generic parameter (for err) must extend the Error object. It defaults to Error.
/**
 * const betterrSync: <TData, TError extends Error = Error>
 * (callback: () => TData) => [TData, null] | [null, TError]
 */

const [user, err] = betterrSync<User, RangeError>(() => ({ id: 1 }));
// data: User | null, err: RangeError | null

Keywords

async-await

FAQs

Package last updated on 05 Sep 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts