Overview
The fromThrowable function wraps a potentially throwing function in a try-catch block and converts it into a function that returns a Result. This is essential when working with third-party libraries or native JavaScript functions that throw exceptions.
fromThrowable is a top-level export that references Result.fromThrowable.
Type Signature
Parameters
fn: The function to wrap (the function that might throw)
errorFn: Optional function to map the caught error to a known type E
- If not provided, the raw error is used as the
Err value
- Recommended to always provide this to ensure type safety
Return Value
Returns a new function with the same parameters as the original, but returns a Result instead of throwing.
Basic Usage
Wrapping JSON.parse
Without Error Mapper (Not Recommended)
Without an error mapper function, the error type will be unknown, which reduces type safety. Always provide an error mapper when possible.
Real-World Examples
Wrapping File System Operations
Wrapping URL Parsing
Wrapping parseInt with Validation
Chaining with Other Methods
Comparison with Try-Catch
Traditional Try-Catch
With fromThrowable
Key Points
- Wraps throwing functions in try-catch
- Returns a new function that returns
Result instead of throwing
- The error mapper function is optional but strongly recommended
- Preserves function parameters and return type
- Makes error handling explicit and type-safe