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 to filter which errors are caught. For catchError, catchErrorSync, and generator APIs, pass the array as a secondary argument. For catchErrorAll and catchErrorAllSync, filters are specified per-input within tuples or configuration objects. If the thrown error is an instance of any class in the filter array, it will be caught and its union type inferred. Otherwise, it will be thrown again.
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.
import { catchErrorSync } from '@catcherjs/core';
const result = catchErrorSync(
() => performComplexTask(),
[ValidationError, DatabaseError, NetworkError]
);
if (result.isErr()) {
console.log(result.error.name);
}Component props
errorsToCatchErrorClass[]