utility function for catching errors, it aims to replace try-catch blocks. it returns a tuple of [error, data] and its fully type safe.
Compare with try-catch
with try and catch
try { const user = await getUser(); } catch (error) { // handle the error }
with tryCatch:
type Data = { name: string; }; type Error = { message: string; status: number; }; const [error, data] = await tryCatch<Data, Error>(getUser()); if (error) { // handle the error } // data is the user object data.name;
the return type is a tuple: either [error, undefined] or [undefined, data]. This enforces type safety by requiring you to handle potential errors before accessing the data.
Installation
Usage
type User = { name: string; }; type Error = { errorMessage: string; }; const [error, user] = tryCatch<User, Error>(getUser()); if (error) { // handle the error console.log(error.errorMessage); } user.name;