Skip to main content

Overview

Wraps a function with a try-catch block, creating a new function with the same arguments but returning Ok if successful and Err if the function throws. This is essential for safely interfacing with third-party libraries and legacy code that use exceptions.

Signature

Parameters

Fn
required
The function to wrap with error handling. Can take any arguments and return any type.
(e: unknown) => E
Optional function to transform the thrown error into a known type. If not provided, the error type will be unknown.

Returns

Returns a new function with the same signature as fn, but returns:
  • Ok(result) if the function executes successfully
  • Err(error) if the function throws (error transformed by errorFn if provided)

Examples

Basic Usage with JSON.parse

With Error Handler

With Arguments

Typed Error Handling

File System Operations

URL Parsing

Database Operations

Parsing User Input

Wrapping Third-Party Libraries

Regex Operations

Real-World Authentication

Implementation Details

From the source code (result.ts:23-35):
Also available as top-level export (result.ts:523):

Notes

  • The wrapper function has the same signature as the original function
  • Without errorFn, the error type is unknown
  • The error handler receives unknown since any type can be thrown in JavaScript
  • Useful for wrapping third-party libraries that throw exceptions
  • Does not catch async errors - for that, use ResultAsync.fromThrowable
  • The original function is called immediately when the wrapper is invoked

Best Practices

  1. Always provide an error handler for better type safety
  2. Create typed error objects instead of using strings
  3. Preserve error information in the error handler
  4. Document what errors can be thrown by the wrapped function
  5. Use for I/O boundaries (parsing, file system, network, databases)