Error Filtering

Catch specific errors and let others crash the app.

Sometimes you only want to catch specific types of errors, such as validation errors, while letting critical errors (like database connection failures) bubble up and crash the application.

You can provide an array of Error classes as a secondary argument. If the thrown error is an instance of any class in the array, it will be caught. Otherwise, it will be thrown again.

error-filter.ts
import { catchErrorSync } from '@catcherjs/core';

class DatabaseError extends Error {
name = 'DatabaseError';
}

class ValidationError extends Error {
name = 'ValidationError';
}

function processUserData() {
const result = catchErrorSync(
() => {
throw new DatabaseError('Connection failed');
},
[ValidationError]
);

  return result;

}

In the example above, the DatabaseError is not in the filter list [ValidationError]. Therefore, catchErrorSync will not return a Result object; instead, it will re-throw the DatabaseError and crash the program, which is often the desired behavior for fatal errors.

You can pass multiple classes to handle different expected failure modes simultaneously.

combined-filters.ts
import { catchErrorSync } from '@catcherjs/core';

const [error, data] = catchErrorSync(
() => performComplexTask(),
[ValidationError, DatabaseError, NetworkError]
);

if (error) {
console.log(error.name);
}

Component props

Prop
Type
Default