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 object and tuple consumption. Because JavaScript can throw falsy values such as undefined, use isOk() or isErr() whenever status must be unambiguous.
This approach mimics the error handling style found in languages like Go.
import { catchErrorSync } from '@catcherjs/core';
const result = catchErrorSync(() => JSON.parse('{"valid": true}'));
if (result.isErr()) {
throw new Error('Parse failed');
}
console.log(result.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();