Simple magic-like utilities to ease your development experience.
npm install trykit
For more in depth documentation about the features, check out the full docs.
safetry
: Call a function without wrapping intry-catch
. Detects and handles errors.tryparse
: Parse data with a schema without throwing.retry
: Retry a function up ton
times.tryto
: Evaluate input with fallback on error.snag
: Chainable error-handling for promises.pipeline
: Chain and execute multiple functions.
safetry<T>(callback: Promise<T> | (() => Promise<T>) | (() => T)): SafeTryResult<T>
- Parameters:
callback
: Function or promise to execute.
- Returns:
SafeTryResult<T>
withsuccess
flag and result or error.
Example:
import { safetry } from "trykit";
const result = await safetry(fetch("/hello"));
if (!result.success) console.error(result.error.message);
console.log(result.data);
tryparse<T>(schema: TryParseSchema<T>, input: unknown, ...args: unknown[]): SafeTryResult<T>
- Parameters:
schema
: Schema with aparse
method.input
: Data to parse.
- Returns:
SafeTryResult<T>
with parsed data or error.
Example:
import { tryparse } from "trykit";
const zodSchema = z.object({ hello: z.string() });
const zodResult = tryparse(zodSchema, { bye: "good day" });
retry<T>(callback: Promise<T> | (() => Promise<T>), config?: RetryConfig): SafeTryResult<T>
- Parameters:
callback
: Function or promise to retry.config
: Retry settings (attempts
,delay
,factor
).
- Returns:
SafeTryResult<T>
with final result or error.
Example:
const result = await retry(fetch("/unknown"), { attempts: 5, delay: 50 });
if (!result.success) console.error(result.error.message);
console.log(result.data);
tryto<T, D>(input: (() => T) | T, fallback: D | (() => D)): T | D
- Parameters:
input
: Value or function to evaluate.fallback
: Fallback value or function.
- Returns:
T | D
(result or fallback).
Example:
import { tryto } from "trykit";
const result = tryto(() => JSON.parse("invalid json"), "fallback");
console.log(result); // 'fallback'
Chain multiple synchronous or asynchronous functions.
- Methods:
.pipe
: Add functions to the chain..execute
: Run the chain.
Example:
import { pipeline } from "trykit";
const result = pipeline((n) => n + 1)
.pipe((n) => n * 2)
.execute(5);
console.log(result); // 12
Chainable error handling utility.
- Parameters:
promise
: Operation to execute.errorType
: Specific error class to catch.handler
: Function to handle the error.
Example:
import { snag } from "trykit";
class DatabaseError extends Error {}
const result = await snag(fetchData)
.on(DatabaseError, (err) => "Cached Data")
.execute("some-id");