Skip to main content

Typing Caught Errors

Error handling in older variations natively of TypeScript or standard JS was extraordinarily flimsy natively.

When catching an error inside a try {} catch (e) {} block, JavaScript doesn't natively know if e is actually a true instantiated Error object cleanly, or just a raw string thrown manually by an angry developer!

The unknown Catch Pattern

In modern high-level strict-mode TypeScript (v4.0+), thrown catch variables are securely mapped as unknown natively (instead of ancient any bypass logic).

Because it structurally maps as unknown, you CANNOT blindly call error.message anymore without Narrowing correctly!

try {
throw new Error("System Crash!");
} catch (error) { // 'error' is structurally defined firmly as 'unknown'

// ERROR: Object is of type 'unknown'.
// console.log(error.message);

// We must strictly narrow the error gracefully to prove it possesses a message!
if (error instanceof Error) {
console.log(error.message); // Legally works securely!
} else if (typeof error === "string") {
console.log(error); // Maps successfully handled custom manual strings safely!
} else {
console.log("Unrecognized terrible error format securely handled.");
}
}