Skip to content

Instantly share code, notes, and snippets.

@swikars1
Last active January 29, 2024 23:23
Show Gist options
  • Save swikars1/e6b10e20d5efadf2533ec04ef57f8f84 to your computer and use it in GitHub Desktop.
Save swikars1/e6b10e20d5efadf2533ec04ef57f8f84 to your computer and use it in GitHub Desktop.
Typescript tryCatch helper function using Rust like Result<T, E> types.
function tryCatch<T>(fn: () => T, andFinally?: () => void): Result<T, string> {
try {
return Ok(fn());
} catch (err) {
return Err(`Fn threw an error ${err}`);
} finally {
andFinally?.();
}
}
const user = {
email: "asd@dsaf.df",
name: "asdas",
};
const stringToTest = JSON.stringify(user);
const typedVal = tryCatch<typeof user>(
() => JSON.parse(stringToTest),
() => {
console.log("parsing was performed");
}
);
const parsedVal = typedVal.unwrapOr({ name: "", email: "" }); //unwrap with default value if err
if (typedVal.isErr()) {
console.log("failed to parse json");
} else {
console.log(typedVal.unwrap());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment