Interoperating Between Result and Exceptions
You'll learn how to build wrapper functions that convert between Result objects and traditional thrown errors, making it easy to integrate Result-based code with exception-throwing libraries.
The Integration Challenge
You've adopted the Result pattern for explicit error handling, but the JavaScript ecosystem is full of libraries that throw exceptions. You need clean boundaries: functions that catch thrown errors and wrap them into Result objects, and functions that unwrap Result objects and throw when needed.
Converting Exceptions to Results
When calling a library that throws, wrap it in a "try-catch boundary":
function tryToResult(fn) {
return function(...args) {
try {
const value = fn(...args);
return { ok: true, value };
} catch (error) {
return { ok: false, error };
}
};
}
// Third-party library throws on invalid input
function parseJSON(text) {
return JSON.parse(text); // throws SyntaxError
}
const safeParseJSON = tryToResult(parseJSON);
const result = safeParseJSON('{"name":"Alice"}');
// { ok: true, value: { name: 'Alice' } }
const badResult = safeParseJSON('not json');
// { ok: false, error: SyntaxError(...) }
Converting Results to Exceptions
When a Result-based function must interface with exception-expecting code:
function resultToThrow(result) {
if (result.ok) {
return result.value;
}
throw result.error;
}
// Usage
const result = safeParseJSON('invalid');
// resultToThrow(result); // throws the wrapped error
These boundary functions act as translators between two error-handling paradigms, letting you use Result internally while playing nicely with external libraries.
Key Takeaway: Use wrapper functions like tryToResult and resultToThrow to create clean boundaries between Result-based code and exception-throwing libraries, allowing both patterns to coexist in the same codebase.