Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

📛 Tiny typescript library to get rid of try catches and use Result (v2)

License

NotificationsYou must be signed in to change notification settings

ahme-dev/tryresult

Repository files navigation

npm bundle sizenpmnpm

📛 TryResult

A tiny typescript library to get rid of try catches, and replace them with result types, inspired by Rust and Go error handling.

preview picture

Under 650 bytes (minified and gzipped) and with no dependencies, TryResult only provides you with more elegant error handling and gives you functions that act as wrappers and catch errors in your own functions.

Install

As with any package, install using your favorite package manager:

pnpm i tryresult

Usage

The base functionality of TryResult revolves around theResult type, which can either be anOk or anErr. You can create these results using theok anderr functions.

import{ok,err,Result,isOk,isErr}from"tryresult";// You can create a Result with a value or an errorconstsuccess=ok("Success!");// Result<string, Error>constfailure=err(newError("Something went wrong"));// Result<string, Error>// You can do typesafe checks of a Resultif(isOk(success)){console.log(success.value);// "Success!"}if(isErr(failure)){console.error(failure.error);// Error: Something went wrong}

Wrapping Functions

To do away with try-catch blocks around functions you can't control, you can use wrapping functions to automatically get aResult type.

import{tryFn,isErr}from"tryresult";// Capture throws from async or sync functionsconstresult=tryFn(()=>{returnJSON.parse('{"message": "Hello!"}');});constasyncResult=awaittryFn(async()=>{constresponse=awaitfetch('https://api.example.com/data');returnresponse.json();});// As shown above, the `Result` can be checkedif(isErr(result)){console.error("An error occurred:",result.error);// Guaranteed to be an Error object}else{console.log(result.value.message);// "Hello!"}

Working with Results

Several utilities are provided to make working withResult types easier, and abstract common functionality.

import{match,okOr,okOrThrow,mapOk,mapErr}from"tryresult";// Match on the Result type to run different logic or return different values based on whether it's Ok or Errconstgreeting=match(result,{ok:(value)=>`Success:${value.message}`,err:(error)=>`Error:${error.message}`,});// Ignore errors and use a default value for when you don't care about the errorconstdata=okOr(result,{message:"Default message"});// If need be, you can throw an error if the Result is Errtry{constvalue=okOrThrow(result);console.log(value.message);}catch(error){console.error("Error was thrown:",error);}// Returned values can be transformed/mapped quicklyconstuppercased=mapOk(result,(value)=>value.toUpperCase());// The same is true for errors, and several mapping functions are providedconstbetterError=mapErr(result,(error)=>`Custom error:${error.message}`);

More information can be found as part of function documentation, which can be viewed in your editor or in the source code.

About

📛 Tiny typescript library to get rid of try catches and use Result (v2)

Topics

Resources

License

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp