TypeScript/Async/Lesson 06
Error Handling — err in catch is unknown; Narrow It Before Use
30 min·theory
This chapter
6/7
TypeScript
Error Handling — err in catch is unknown; Narrow It Before Use
💡 Why Does This Matter? — Catching an Error Doesn't Mean You're Done
🎯
In JS, `catch` types `err` as `any` — you can access `.message` without any checks. TS forces `unknown`, making you verify 'is this really an Error?' before proceeding.
💼
`throw` can throw anything — an Error, a string, a number, an object. Assuming a shape inside `catch` is dangerous.
⚡
Classifying errors with custom Error classes (ApiError, ValidationError, etc.) lets call sites handle each case differently.
🔗
`try/finally` guarantees resource cleanup (closing files, releasing locks) — it runs whether or not an error is thrown.
🏢 실무에서는
API call failures require different UX for 401/403/404/500: 401 → redirect to login, 403 → show permission notice, 404 → show empty state, 500 → show temporary error message. To branch on `err.status === 401` in `catch`, you need to know the type of the error object — TypeScript's `instanceof ApiError` is the safe entry point for that.
Narrowing unknown · Custom Error · try/finally
1. err in catch (err) is unknown (TS 4.4+)
2. Three Patterns for Narrowing
3. Custom Error Classes — Classify Your Errors
At the call site:
4. try/finally — Cleanup Always Runs
💡 💡 Top 5 TypeScript Error Handling Essentials
1. err in catch is unknown — narrow it
2. Build custom Error classes and always set name
3. Use instanceof to classify errors
String comparisons like err.code === 'XYZ' risk typos and duplication. Class-based checks are safe at compile time.
4. finally always runs — use it for cleanup
Closing files, releasing database connections, releasing locks — put these in finally.
5. Never write an empty catch
At minimum, log with console.error(err). Otherwise, rethrow.
⚡ Try It Yourself — Custom Error + instanceof
Throw different error types and handle them with branching logic in catch.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.
Check Your Understanding
What is the safest way to narrow `err` in `catch (err) { ... }` in TypeScript?
Read this first: Fetch API — Generic Helper fetchJson<T>