The type of data returned by the successful operation
The type of error returned, defaults to ErrorWithStatus
A sync function, async function, or Promise to execute safely
Optionaloptions: TryCatchOptions<E>Configuration options for error handling behavior
Result<T, E> for sync functions, Promise<Result<T, E>> for async/Promise inputs
const { data, error } = await tryCatch(async () => {
const user = await getUser();
const profile = await getProfile(user.id);
return { user, profile };
});
class ApiError extends Error {
constructor(message: string, public status?: number) {
super(message);
}
}
const { data, error } = await tryCatch(fetchApiData(), {
ErrorClass: ApiError,
defaultStatus: 500
});
const result = tryCatch(() => JSON.parse(raw));
if (isFailure(result)) {
console.error(result.error.message);
} else {
console.log(result.data);
}
Wraps an operation and returns a Result object instead of throwing exceptions.
Result<T, E> directly (no Promise)Promise<Result<T, E>>The type of data returned by the successful operation
The type of error returned, defaults to ErrorWithStatus
Optionaloptions: TryCatchOptions<E>Configuration options for error handling behavior
Result<T, E> for sync functions, Promise<Result<T, E>> for async/Promise inputs
const { data, error } = await tryCatch(async () => {
const user = await getUser();
const profile = await getProfile(user.id);
return { user, profile };
});
class ApiError extends Error {
constructor(message: string, public status?: number) {
super(message);
}
}
const { data, error } = await tryCatch(fetchApiData(), {
ErrorClass: ApiError,
defaultStatus: 500
});
const result = tryCatch(() => JSON.parse(raw));
if (isFailure(result)) {
console.error(result.error.message);
} else {
console.log(result.data);
}
Wraps an operation and returns a Result object instead of throwing exceptions.
Result<T, E>directly (no Promise)Promise<Result<T, E>>