Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I create a custom error class in JavaScript and handle it with try/catch to provide detailed error messages?
Asked on Dec 24, 2025
Answer
To create a custom error class in JavaScript, extend the built-in Error class. This allows you to throw and catch custom errors with detailed messages.
<!-- BEGIN COPY / PASTE -->
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
try {
throw new CustomError("This is a custom error message.");
} catch (error) {
if (error instanceof CustomError) {
console.error(`Custom error caught: ${error.message}`);
} else {
console.error(`General error caught: ${error.message}`);
}
}
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This example defines a "CustomError" class that extends the "Error" class.
- The "try" block throws a "CustomError" with a specific message.
- The "catch" block checks if the error is an instance of "CustomError" and logs a custom message.
- If the error is not a "CustomError", it logs a general error message.
Recommended Links:
