JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What are custom errors in JavaScript?

Asked on Aug 28, 2024

Answer

Custom errors in JavaScript allow you to create error types that are specific to your application's needs, enhancing error handling and debugging. Here's how you can define and use a custom error class:
<!-- 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) {
            console.error(error.name + ": " + error.message);
        }
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "CustomError" class extends the built-in "Error" class.
  • The "constructor" sets the error message and assigns a custom name to the error.
  • The "try...catch" block demonstrates how to throw and catch a custom error.
  • Custom errors provide more context and specificity, aiding in debugging and error management.
✅ Answered with JavaScript best practices.
← Back to All Questions