A lightweight, low overhead errors-as-values API.
Features:
- Error type safety.
- No wrapping for success path.
- Minimal runtime cost.
import*asstfrom'@safe-std/error';Create a new error.
constvalue=st.err('An error occured!');// st.Err<'An error occured!'>value.payload;// 'An error occured'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}Represents a generic error with no payload.
st.error;// st.Err<undefined>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}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}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}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: ... }}