Skip to content

Repository files navigation

A lightweight, low overhead errors-as-values API.

Features:

  • Error type safety.
  • No wrapping for success path.
  • Minimal runtime cost.

API

import*asstfrom'@safe-std/error';

st.err(payload)

Create a new error.

constvalue=st.err('An error occured!');// st.Err<'An error occured!'>value.payload;// 'An error occured'

st.isErr(value)

Check whether value is an error.

constvalue=Math.random()<0.5 ? 0 : st.err('Random');if(st.isErr(value)){value.payload;// 'Random'}else{value;// 0}

st.error

Represents a generic error with no payload.

st.error;// st.Err<undefined>

tryPromise(promise)

Safely catch errors from promise.

// Safely catch fetch call errorconstresponse=awaitst.tryPromise(fetch('http://example.com'));if(st.isErr(response)){response.payload;// unknown}else{response;// Response}

tryAsync(fn)

Create a new function that wraps async function fn errors safely.

constresponse=st.tryAsync(fetch,'http://example.com');if(st.isErr(response)){response.payload;// unknown}else{response;// Response}

trySync(fn)

Create a new function that wraps sync function fn errors safely.

constresult=trySync(decodeURIComponent,'%FF%G0');if(st.isErr(result)){result.payload;// unknown}else{result;// string}

Tagging error

declareconsthttpErrSymbol: unique symbol;// Prevent HttpErr from being assignable to Err with equivalent payloadinterfaceHttpErr{[httpErrSymbol]: null;}classHttpErrextendsst.Err<{status: number,statusText: string}>{};constbadReq=newHttpErr({status: 400,statusText: 'Bad request'});badReq.payload;// { status: 400, statusText: 'Bad request' }// Error checkingif(errinstanceofHttpErr){err.payload;// { status: ..., statusText: ... }}

About

Minimal, type-safe error-as-values library for JS

Resources

Stars

21 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages