Skip to content

Repository files navigation

attempted

ci

Typed error handling for calling functions

Docs

https://testingrequired.github.io/attempted

Install

$ npm install @testingrequired/attempted

https://www.npmjs.com/package/@testingrequired/attempted

Example

import{Attempt}from"@testingrequired/attempted";letattempt: Attempt<number>=Attempt.of(fnMightThrow, ...fnArgs);// Returns true if function didn't throw or returned a failed attemptattempt.isSuccessful();// Returns true if function throws or returned a failed attemptattempt.isFailure();// You can conditionally run functions on successful or failed attemptsattempt.ifSuccessful((value)=>{});attempt.ifFailure((error)=>{});attempt.ifElse((value)=>{},(error)=>{});// Map over successful attempts// This will not run on a failed attemptattempt=attempt.map((n)=>n*2);// Assert over successful attempts// Failed assertions will return a failed attempt// This will not run on a failed attemptattempt=attempt.assert((value)=>value>100,(value)=>`Value ${value} was less than 100`);// Returns value on successful attempts// Throws on failed attemptsattempt.get();// Returns error on failed attempts// Throws on successful attemptsattempt.getError();// Get value on successful attempts or a default value.attempt.orElse(defaultValue);// Get value or throw provided errorattempt.orThrow(newError("Something went wrong"));attempt.orThrow("Something went wrong");// You can pass function to access a failed attempt's errorattempt.orThrow((error)=>newError(`Something went wrong: ${e}`));attempt.orThrow((error)=>`Something went wrong`);

It also works with async functions!

import{Attempt}from"@testingrequired/attempted";// Await the attempt the same as you would await the function callletattempt: Attempt<number>=awaitAttempt.of(asyncFnMightThrow, ...fnArgs);// You can use async functions to map as wellattempt=awaitattempt.map(async(n)=>n*2);// Returns the attempts valueattempt.get();

Contributing

See CONTRIBUTING.md.

About

Typed error handling for functions

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages