JavaScript Course
JavaScript
/
Intermediate

Custom Errors

Definition

Creating custom error classes that extend the built-in JavaScript `Error` object to provide more specific and actionable error handling.

Explain Like I'm New

Standard errors just say 'Something went wrong'. A custom error says 'The Database Connection Timed Out'. This allows your `catch` block to look at the error and say, 'Oh, it's a Database error, I will retry 3 times. If it was a Validation error, I won't retry.'

Real World Example

Creating a `ValidationError` class. If a user submits a bad email, you throw a `ValidationError`. Your catch block checks `if (err instanceof ValidationError)` and displays it to the user, but if it's a standard `Error`, it sends it to the crash reporting tool.

Common Use Cases

  • •API error handling
  • •Domain-specific logic rules

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • How do you manually throw an error in JavaScript?

intermediate

  • How do you create a custom error class?

advanced

  • Why is extending the built-in `Error` class important for stack traces?

Flash Cards

Question

How do you manually throw an error?

Click to reveal answer
Answer

Using the `throw` keyword: `throw new Error("Invalid ID");`. You can technically throw anything (even a string: `throw "Crash"`), but it's terrible practice because you lose the stack trace.

Question

Why is extending Error important?

Click to reveal answer
Answer

The native `Error` class automatically captures the Stack Trace (the exact file and line number where the error occurred). If you just return a plain object `{ message: 'failed' }`, you will have no idea where the code failed.