New:Microsoft Teams Notifications Are Now Available in Socket.Learn more
Get Started

ts-try-async

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-try-async

TypeScript-first async error handling utility with typed Result pattern

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

ts-try-async

TypeScript-first async error handling utility with typed Result pattern.

Convert thrown exceptions into typed, predictable result objects — no more try/catch blocks scattered everywhere.

Installation

npm install ts-try-async

Usage

Basic Usage

import { tryAsync } from 'ts-try-async'

const result = await tryAsync(() => fetchUser(id))

if (result.success) {
  console.log(result.result) // User object, fully typed
} else {
  console.log(result.message) // Error message string
  console.log(result.cause)   // Original error for debugging
}

TypeScript automatically narrows the type — result.result only exists when success === true.

With Error Callback

const result = await tryAsync(
  () => fetchUser(id),
  {
    onError: (error, message) => {
      // error: full Error object with stack trace
      // message: normalized string
      Sentry.captureException(error)
      logger.error(message)
    }
  }
)

Higher-Order Function

Wrap a function once, reuse everywhere:

import { withTryAsync } from 'ts-try-async'

const safeFetchUser = withTryAsync(fetchUser)

const result = await safeFetchUser(id) // Returns AsyncResult<User>

With options:

const safeFetchUser = withTryAsync(fetchUser, {
  onError: (error) => Sentry.captureException(error)
})

API

tryAsync<T>(fn, options?): Promise<AsyncResult<T>>

Executes an async function and returns a result object.

ParameterTypeDescription
fn() => Promise<T>Async function to execute
options.onError(error: unknown, message: string) => voidOptional error callback

withTryAsync<TArgs, TReturn>(fn, options?)

Wraps an async function to return AsyncResult instead of throwing.

ParameterTypeDescription
fn(...args: TArgs) => Promise<TReturn>Async function to wrap
options.onError(error: unknown, message: string) => voidOptional error callback

Types

type AsyncResult<T> = AsyncSuccess<T> | AsyncError

interface AsyncSuccess<T> {
  success: true
  result: T
}

interface AsyncError {
  success: false
  message: string
  cause: unknown
}

interface TryAsyncOptions {
  onError?: (error: unknown, message: string) => void
}

Why?

  • Type-safe: Discriminated unions enable automatic type narrowing
  • Predictable: Errors become data, not exceptions
  • Minimal: Zero dependencies, ~50 lines of code
  • Flexible: Access full error via cause or onError callback

License

MIT

Keywords

typescript

FAQs

Package last updated on 22 Dec 2025

Related posts