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.
https://github.com/syhner/betterr.git
A better way to handle errors
Unlike with try...catch or promises:
$ npm install betterr
import { betterr } from 'betterr'; // const { betterr } = require('betterr');
const [user, err] = await betterr(() => getUserWithId(1));
// user: User | null, err: Error | null
const maybeName = user?.name; // maybeName: string | undefined
if (err) return; // user: User (after error handled)
const name = user.name; // name: string
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.Both betterr and betterrSync are generic.
data). It defaults to the callback return type.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