In strict TypeScript, errors caught inside try...catch blocks are typed as unknown (or any). Proper error handling requires narrowing caught errors before accessing properties like error.message.
flowchart TD
A["try { ... } catch (err)"] --> B["err is typed as unknown"]
B --> C{"err instanceof Error?"}
C -- "Yes" --> D["Access err.message & err.stack cleanly"]
C -- "No" --> E["Handle raw string / unknown throw payload"]
// Custom Domain Error Class
export class DatabaseConnectionError extends Error {
public readonly code: string = "DB_CONN_FAILED";
constructor(message: string, public readonly host: string) {
super(message);
this.name = "DatabaseConnectionError";
Object.setPrototypeOf(this, DatabaseConnectionError.prototype);
}
}
function connectToDatabase(host: string): void {
if (host === "invalid_host") {
throw new DatabaseConnectionError("Failed to resolve database host", host);
}
console.log(`Successfully connected to ${host}`);
}
// Type-Safe Error Handling
try {
connectToDatabase("invalid_host");
} catch (err: unknown) {
if (err instanceof DatabaseConnectionError) {
console.error(`[${err.code}] ${err.message} (Host: ${err.host})`);
} else if (err instanceof Error) {
console.error(`Standard Error: ${err.message}`);
} else {
console.error("Unknown throw payload:", err);
}
}
Object.setPrototypeOf(this, CustomError.prototype) inside custom Error constructors to ensure instanceof works properly across ES targets.throw new Error(...) instead of throwing raw primitives like throw "something failed".{ ok: true, value: T } | { ok: false, error: E } instead of relying on throw for non-exceptional business logic.What is the type of err inside catch (err) when useUnknownInCatchVariables or strict is enabled? (Answer: unknown)
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With