Skip to content

Instantly share code, notes, and snippets.

@juxuanu
Last active January 30, 2025 14:37
Show Gist options
  • Save juxuanu/4de72bbb82800c98971d7183af947ce2 to your computer and use it in GitHub Desktop.
Save juxuanu/4de72bbb82800c98971d7183af947ce2 to your computer and use it in GitHub Desktop.
class Error {
public readonly generatedAt: Date;
constructor(public readonly message: string) {
this.generatedAt = new Date();
}
}
const isError = (input: unknown): input is Error => input instanceof Error;
function tryFn<F extends (...args: any[]) => any>(
fn: F,
...input: Parameters<F>
): ReturnType<F> | Error {
let result: ReturnType<F> | Error;
try {
result = fn(input);
} catch (e) {
result = new Error(e.toString());
}
return result;
}
const something = async () => {
const log = (i: string) => `I logged: ${i}`;
const resultSync = tryFn(log, 'hi');
if (isError(resultSync)) {
console.error(`[Sync ERROR at ${resultSync.generatedAt}] ${resultSync.message}`);
} else {
console.info(resultSync); // type is correct
}
const sleep = async () => setTimeout(null, 1000);
const resultAsync = await tryFn(sleep);
if (isError(resultAsync)) {
console.error(`[Async ERROR at ${resultAsync.generatedAt}] ${resultAsync.message}`);
} else {
console.info(resultAsync); // type is correct
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment