← Back to TypeScript Course | Chapter 15: TypeScript with APIs | Lesson 4 of 6

Types के साथ Error Handling

API calls network problems, invalid responses, या server errors की वजह से fail हो सकती हैं। TypeScript का unknown type और custom error types failures को सुरक्षित तरीके से handle करने में मदद करते हैं बिना यह मान लिए कि हर caught value एक Error है।
Syntax
typescript
try {
  // code
} catch (error) {
  if (error instanceof Error) {
    console.error(error.message);
  }
}

Catch Blocks में unknown

TypeScript एक catch block में caught exception को default रूप से unknown type करता है, जो आपको .message जैसी properties को सुरक्षित रूप से access करने से पहले इसे narrow करने — आमतौर पर instanceof Error से — पर मजबूर करता है।

उदाहरण: unknown in Catch Blocks

typescript
try {
  throw new Error("Something failed");
} catch (err: unknown) {
  if (err instanceof Error) console.log(err.message);
}

Custom API Errors

Error extend करने वाली एक custom API error class एक status code जैसे extra typed fields ले जा सकती है, catch blocks को एक generic error message string parse करने के बजाय specific error types पर branch करने देते हुए।

उदाहरण: Custom API Errors

typescript
class ApiError extends Error {
  constructor(message: string, public statusCode: number) {
    super(message);
  }
}
try {
  throw new ApiError("Not found", 404);
} catch (err) {
  if (err instanceof ApiError) console.log(err.statusCode);
}

API Errors के लिए Result Types

एक Result type — जैसे { ok: true, data: T } | { ok: false, error: E } — API calls के लिए error handling को return type में ही explicit बनाता है, callers को data छूने से पहले ok जांचने पर मजबूर करते हुए।

उदाहरण: Result Types for API Errors

typescript
type Result<T, E> = { ok: true; data: T } | { ok: false; error: E };
function parse(input: string): Result<number, string> {
  const n = Number(input);
  return isNaN(n) ? { ok: false, error: "Invalid number" } : { ok: true, data: n };
}
const result = parse("42");
if (result.ok) console.log(result.data);

HTTP Error Handling

HTTP errors को specifically handle करने का मतलब है response status code जांचना और इसे एक typed error से map करना (जैसे एक 404 को 500 से अलग करना) बजाय हर failed request को उसी generic तरीके से treat करने के।

उदाहरण: HTTP Error Handling

typescript
function classify(status: number): string {
  if (status === 404) return "Not Found";
  if (status >= 500) return "Server Error";
  return "Unknown";
}
console.log(classify(404));

Error और Result Types Combine करना

एक Result type को typed custom errors के साथ combine करना आपको एक explicit success/failure branch और failure branch के अंदर detailed error information दोनों देता है, बिना throw/catch के untyped exception flow पर बिल्कुल भी भरोसा किए।

उदाहरण: Combining Error and Result Types

typescript
class ApiError extends Error {
  constructor(message: string, public statusCode: number) { super(message); }
}
type Result<T> = { ok: true; data: T } | { ok: false; error: ApiError };
function fetchUser(): Result<string> {
  return { ok: false, error: new ApiError("Not found", 404) };
}
const result = fetchUser();
if (!result.ok) console.log(result.error.statusCode);
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. catch block में err.message को narrow किए बिना access करना, जब value unknown है।
  2. throw "failed" जैसी plain strings throw करना, जो stack trace खो देता है और instanceof Error checks तोड़ देता है।
  3. एक custom error class में super(message) भूल जाना, जो एक compile error है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.