Core Concepts
Understanding the Result pattern and the dual API.
The Catcher is built around the Result pattern. Instead of throwing exceptions that interrupt the control flow, operations return a Result object that encapsulates either a successful outcome or an error.
The Result object returned by the library implements both standard object properties and a true tuple union structure ([E, undefined] | [undefined, T]). This allows you to consume the result in two distinct ways with perfect TypeScript type narrowing.
This approach mimics the error handling style found in languages like Go.
import { catchErrorSync } from '@catcherjs/core';
const [error, data] = catchErrorSync(() => JSON.parse('{"valid": true}'));
if (error) {
throw new Error('Parse failed');
}
console.log(data.valid);This approach uses fluent methods to check the status and retrieve values.
import { catchErrorSync } from '@catcherjs/core';
const result = catchErrorSync(() => JSON.parse('{"valid": true}'));
if (result.isOk()) {
console.log(result.data.valid);
} else {
console.error(result.error);
}When using the Object API, several helper methods are available on the Result object.
Returns the successful data if the operation succeeded, or a provided fallback value if it failed.
const result = catchErrorSync(() => JSON.parse('invalid'));
const parsedData = result.getOrElse({ default: true });Returns the successful data if the operation succeeded, but throws the encapsulated error if it failed.
const result = catchErrorSync(() => JSON.parse('{"valid": true}'));
const data = result.unwrap();