← Back to JavaScript Course | Chapter 8: Error Handling | Lesson 3 of 6

JS कस्टम Errors

एक custom error आपके अपने नाम और details वाला एक error type है, जैसे आपके अपने घर के लिए बनाया गया एक खास warning sign। यह समस्याओं को पहचानना और संभालना आसान बनाता है।
Syntax
javascript
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}

throw new CustomError("message");

Custom Errors बनाना

आप built-in Error class को extend करके एक custom error type बनाते हैं, जो आपके नए error को message property और एक proper stack trace जैसा inherited व्यवहार देता है, साथ ही आपको ऊपर से अपने खुद के fields जोड़ने देता है।

उदाहरण: Creating Custom Errors

javascript
// Define the class `ValidationError`, inheriting from `Error`
// Define the class `ValidationError`, inheriting from `Error`
class ValidationError extends Error {
  // Constructor taking `message`, runs when a new instance is created
  // Constructor taking `message`, runs when a new instance is created
  constructor(message) {
    // Call `super(message)`
    // Call `super(message)`
    super(message);
    // Assign "ValidationError" to `this.name`
    // Assign "ValidationError" to `this.name`
    this.name = "ValidationError";
  }
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Throw a new `ValidationError` with message "Invalid email"
  // Throw a new `ValidationError` with message "Invalid email"
  throw new ValidationError("Invalid email");
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `e.name, e.message` to the console
  // Print `e.name, e.message` to the console
  console.log(e.name, e.message);
}

अतिरिक्त जानकारी जोड़ना

एक custom error class अतिरिक्त constructor arguments स्वीकार कर सकता है और उन्हें additional properties के रूप में store कर सकता है, जो catch blocks को एक साधारण message string से आगे structured details access करने देता है।

उदाहरण: Adding Extra Information

javascript
// Define the class `ValidationError`, inheriting from `Error`
// Define the class `ValidationError`, inheriting from `Error`
class ValidationError extends Error {
  // Constructor taking `message`, `field`, runs when a new instance is created
  // Constructor taking `message`, `field`, runs when a new instance is created
  constructor(message, field) {
    // Call `super(message)`
    // Call `super(message)`
    super(message);
    // Assign "ValidationError" to `this.name`
    // Assign "ValidationError" to `this.name`
    this.name = "ValidationError";
    // Assign `field` to `this.field`
    // Assign `field` to `this.field`
    this.field = field;
  }
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Throw a new `ValidationError` with message "Required field", "email"
  // Throw a new `ValidationError` with message "Required field", "email"
  throw new ValidationError("Required field", "email");
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `e.field, e.message` to the console
  // Print `e.field, e.message` to the console
  console.log(e.field, e.message);
}

Custom Errors को Catch करना

चूंकि एक custom error अभी भी Error को extend करता है, मौजूदा try/catch code काम करता रहता है; आप उस खास error type को अलग तरीके से संभालने के लिए error instanceof YourErrorClass भी जांच सकते हैं।

उदाहरण: Catching Custom Errors

javascript
class ValidationError extends Error {}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Throw a new `ValidationError` with message "Bad input"
  // Throw a new `ValidationError` with message "Bad input"
  throw new ValidationError("Bad input");
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `e instanceof ValidationError` to the console
  // Print `e instanceof ValidationError` to the console
  console.log(e instanceof ValidationError);
  // Print `e instanceof Error` to the console
  // Print `e instanceof Error` to the console
  console.log(e instanceof Error);
}

Custom Error के Use Cases

Custom errors तब उपयोगी हैं जब अलग-अलग failure categories को अलग handling चाहिए — उदाहरण के लिए, एक ValidationError बनाम एक NetworkError बिल्कुल अलग UI responses trigger कर सकता है।

उदाहरण: Custom Error Use Cases

javascript
class ValidationError extends Error {}
class NetworkError extends Error {}
// Define the function `handle` taking `err`
// Define the function `handle` taking `err`
function handle(err) {
  if (err instanceof ValidationError) console.log("Show form message");
  else if (err instanceof NetworkError) console.log("Retry request");
}
// Call `handle(new NetworkError("timeout"))`
// Call `handle(new NetworkError("timeout"))`
handle(new NetworkError("timeout"));

Custom Error Best Practices

Custom error classes को साफ नाम दें (convention के हिसाब से Error पर खत्म होते हुए) और उनकी अतिरिक्त properties को कम और अच्छे से documented रखें ताकि दूसरे developers जानें कि उन्हें catch करते समय क्या उम्मीद करनी है।

उदाहरण: Custom Error Best Practices

javascript
// Define the class `OutOfStockError`, inheriting from `Error`
// Define the class `OutOfStockError`, inheriting from `Error`
class OutOfStockError extends Error {
  // Constructor taking `item`, runs when a new instance is created
  // Constructor taking `item`, runs when a new instance is created
  constructor(item) {
    // Call `super(`${item} is out of stock`)`
    // Call `super(`${item} is out of stock`)`
    super(`${item} is out of stock`);
    // Assign "OutOfStockError" to `this.name`
    // Assign "OutOfStockError" to `this.name`
    this.name = "OutOfStockError";
    // Assign `item` to `this.item`
    // Assign `item` to `this.item`
    this.item = item;
  }
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Throw a new `OutOfStockError` with message "Widget"
  // Throw a new `OutOfStockError` with message "Widget"
  throw new OutOfStockError("Widget");
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `e.name, e.item` to the console
  // Print `e.name, e.item` to the console
  console.log(e.name, e.item);
}
Live Example
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. Error को extend करना और super(message) भूल जाना, जो constructor में ReferenceError throw करता है।
  2. this.name set करना भूल जाना, इसलिए error एक plain Error की तरह दिखता है।
  3. message text compare करके errors check करना, जबकि custom class पर instanceof ज़्यादा reliable है।
🔒

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.