ts-try-async
v1.0.1
Published
TypeScript-first async error handling utility with typed Result pattern
Maintainers
Readme
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-asyncUsage
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.
| Parameter | Type | Description |
|-----------|------|-------------|
| fn | () => Promise<T> | Async function to execute |
| options.onError | (error: unknown, message: string) => void | Optional error callback |
withTryAsync<TArgs, TReturn>(fn, options?)
Wraps an async function to return AsyncResult instead of throwing.
| Parameter | Type | Description |
|-----------|------|-------------|
| fn | (...args: TArgs) => Promise<TReturn> | Async function to wrap |
| options.onError | (error: unknown, message: string) => void | Optional 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
causeoronErrorcallback
License
MIT
