AI Hints
Home›TypeScript Tutorial›Async and Outside Data
TypeScript · Lesson 81 of 120

Errors in catch

Unknown errors.

⏱ 2 min read▶ Video at 1:03:11🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Anything can be thrown in JavaScript, not just errors. So in strict mode, the value in a catch block is unknown. You must check it before using it.

Errors in catch
From the video: Errors in catch
  • Anything can be thrown
  • catch gives unknown
  • Check first

Using it unchecked

We read the message from the caught value directly. Run it. TypeScript says it's unknown.

app.tstypescript
try {
  JSON.parse("not json");
} catch (e) {
  console.log(e.message);
}
Output
app.ts line 4: 'e' is of type 'unknown'.

Checking first

Instance of error narrows it. Anything else, we turn into a string. We request a page that doesn't exist. Run it. The error is handled safely.

app.tstypescript
import { get } from "./shop-api.js";

try {
  await get("/orders/9999");
} catch (e) {
  const message = e instanceof Error ? e.message : String(e);
  console.log("Failed:", message);
}
Output
Failed: 404 Not Found: /orders/9999
Also uses shop-api.ts
const DATA: Record<string, unknown> = {
  "/bikes": [{ model: "Trail 500", price: 849.5 }, { model: "Volt 7", price: 2199 }],
  "/orders/1042": { id: 1042, status: "shipped", total: 65 },
  "/orders/1043": { id: 1043, status: "packing", total: "thirty" },
};

export async function get(path: string): Promise<unknown> {
  await new Promise(resolve => setTimeout(resolve, 100));   // pretend network delay
  if (!(path in DATA)) throw new Error(`404 Not Found: ${path}`);
  return structuredClone(DATA[path]);
}

Summary

Caught values are unknown, so check instance of error first. Next, validating data.

Key takeaways
  • catch (e: unknown)
  • instanceof Error
  • String(e)
Next up: Validating Data — runtime checks