Sync Operations
Handling synchronous functions cleanly.
For synchronous operations, the library provides catchErrorSync. It executes a callback function and catches any errors that occur during its execution.
A common use case is safely parsing JSON strings.
parsing.ts
import { catchErrorSync } from '@catcherjs/core';
const jsonString = '{ invalid: json }';
const [error, data] = catchErrorSync(() => JSON.parse(jsonString));
if (error) {
console.log(error.message);
} else {
console.log(data);
}You can also wrap validation functions that might throw exceptions.
validation.ts
import { catchErrorSync } from '@catcherjs/core';
function validateAge(age: number) {
if (age < 18) {
throw new Error('Age must be at least 18');
}
return true;
}
const result = catchErrorSync(() => validateAge(16));
if (result.isErr()) {
console.error(result.error.message);
}Be aware that JavaScript allows throwing any value, not just Error instances. The catchErrorSync function will safely catch strings, numbers, or objects that are thrown.
Component props
Prop
Type
Default
Name
fnDescription
The synchronous function to execute.
Type
() => TDefault
-
Name
errorsToCatchDescription
Optional array of Error classes to catch. If omitted, all errors are caught.
Type
ErrorClass[]Default
-
Name
returnsDescription
A Result object containing either the returned value or the caught error.
Type
Result<T, E>Default
-