Overview
Wraps a function with a try-catch block, creating a new function with the same arguments but returningOk 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 asfn, but returns:
Ok(result)if the function executes successfullyErr(error)if the function throws (error transformed byerrorFnif 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):Notes
- The wrapper function has the same signature as the original function
- Without
errorFn, the error type isunknown - The error handler receives
unknownsince 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
- Always provide an error handler for better type safety
- Create typed error objects instead of using strings
- Preserve error information in the error handler
- Document what errors can be thrown by the wrapped function
- Use for I/O boundaries (parsing, file system, network, databases)
Related
- ResultAsync.fromThrowable() - Async version
- fromThrowable() - Top-level export
- Result.fromPromise() - For promises that may reject