Advanced Result API

Chaining, mapping, and side-effects on Result objects.

The Result object provides a rich, fluent API heavily inspired by functional programming. These methods allow you to chain operations, transform data, and trigger side-effects without breaking the control flow.

Transforms the success data using a provided function. If the result is an error, it ignores the function and returns the error as-is.

map-usage.ts
import { catchErrorSync } from '@catcherjs/core';

const result = catchErrorSync(() => JSON.parse('{"count": 5}'));

const doubled = result.map(data => data.count * 2);

console.log(doubled.unwrap()); 

Transforms the error using a provided function. If the result is a success, it returns the success as-is.

error-mapping.ts
const result = catchErrorSync(() => { throw new Error('Not found') });

const customErrorResult = result.mapErr(err => new CustomError(err.message));

Chains another operation that also returns a Result. If the first operation fails, the chained operation is skipped. Both andThen and flatMap are identical aliases.

chaining.ts
const processData = (raw: string) => {
  return catchErrorSync(() => JSON.parse(raw))
      .andThen(parsed => catchErrorSync(() => validateSchema(parsed)));
};

Recovers from an error by returning a new Result. If the original result is a success, it ignores the function and returns the success as-is.

recovery.ts
const result = catchErrorSync(() => fetchFromCache())
  .orElse(() => catchErrorSync(() => fetchFromDatabase()));

Executes a side-effect (like logging) if the result is a success. It does not modify the Result and returns it unchanged, allowing further chaining.

side-effects.ts
const result = catchErrorSync(() => computeValue())
  .tap(data => console.log('Successfully computed:', data))
  .map(data => data * 2);

Executes a side-effect if the result is an error.

error-logging.ts
const result = catchErrorSync(() => riskyOperation())
  .tapErr(err => console.error('Operation failed:', err.message));

Returns the contained error if the result is a failure. Throws the contained data if it is a success (the opposite of unwrap).

Converts the Result back into a standard Promise. Resolves with the data on success, or rejects with the error on failure.

promise-conversion.ts
const result = catchErrorSync(() => 42);
const value = await result.toPromise();

Component props

Prop
Type
Default