Last active
January 29, 2024 23:23
-
-
Save swikars1/e6b10e20d5efadf2533ec04ef57f8f84 to your computer and use it in GitHub Desktop.
Typescript tryCatch helper function using Rust like Result<T, E> types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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