Skip to content

Instantly share code, notes, and snippets.

View Joseph-Martre's full-sized avatar

Joseph Martin Joseph-Martre

  • France
View GitHub Profile
@Joseph-Martre
Joseph-Martre / try-catch.ts
Last active April 21, 2025 16:57 — forked from t3dotgg/try-catch.ts
Theo's preferred way of handling try/catch in TypeScript
/**
* Coerces an unknown value into an Error type if it is not an instance of
* Error. The original unknown value is still accessible as the cause of the
* coerced error.
*/
function coerceToError(thrown: unknown) {
if (thrown instanceof Error) return thrown;
return new Error("COERCED_NON_ERROR_VALUE", { cause: thrown });
}