Skip to main content

Command Palette

Search for a command to run...

JavaScript Custom Error Classes: Building the ApiError

Learn to create custom JavaScript error classes like `ApiError` for enhanced error handling and debugging in your applications

Updated
3 min read
JavaScript Custom Error Classes: Building the ApiError

Error handling is a critical aspect of robust software development. JavaScript, with its built-in Error class, provides a solid foundation for error management. However, for more specific and meaningful error handling, creating custom error classes is often necessary. This blog post will guide you through creating a custom error class named ApiError, enhancing your application's error handling capabilities.

Why Create Custom Error Classes?

Custom error classes allow you to:

  • Provide more descriptive and meaningful error messages.

  • Include additional properties for more detailed error information.

  • Ensure consistent error handling across your application.

  • Facilitate debugging by capturing detailed error context.

    Implementation of the ApiError Class

    Here is the ApiError class:

      javascriptCopy codeclass ApiError extends Error {
          constructor(
              statusCode,
              message = "Something went wrong",
              errors = [],
              stack = ""
          ) {
              super(message);
              this.statusCode = statusCode;
              this.data = null;
              this.message = message;
              this.success = false;
              this.errors = errors;
    
              if (stack) {
                  this.stack = stack;
              } else {
                  Error.captureStackTrace(this, this.constructor);
              }
          }
      }
    
      export { ApiError };
    

    Detailed Explanation

    1. Extending the Error Class

      javascriptCopy codeclass ApiError extends Error {
    

    The ApiError class extends JavaScript’s built-in Error class. This inheritance allows ApiError to function like a standard error while also including additional custom properties.

    2. Constructor Method

    The constructor method initializes an instance of the ApiError class with several custom properties.

      javascriptCopy codeconstructor(
          statusCode,
          message = "Something went wrong",
          errors = [],
          stack = ""
      ) {
          super(message);
    
    • statusCode: The HTTP status code associated with the error.

    • message: A descriptive error message, defaulting to "Something went wrong".

    • errors: An array of additional error details, defaulting to an empty array.

    • stack: The error stack trace.

The super(message) call invokes the constructor of the parent Error class with the provided message.

3. Setting Properties

    javascriptCopy codethis.statusCode = statusCode;
    this.data = null;
    this.message = message;
    this.success = false;
    this.errors = errors;

These lines set the properties of the ApiError instance:

  • statusCode: Stores the HTTP status code for the error.

  • data: Initialized to null for additional data storage.

  • message: Stores the error message.

  • success: Set to false indicating the operation was unsuccessful.

  • errors: Stores any additional error details.

4. Handling the Stack Trace

    javascriptCopy codeif (stack) {
        this.stack = stack;
    } else {
        Error.captureStackTrace(this, this.constructor);
    }
  • If a custom stack trace is provided (stack), it assigns it to the instance’s stack property.

  • If no custom stack trace is provided, Error.captureStackTrace captures the current stack trace and associates it with the ApiError class.

Exporting the Class

    javascriptCopy codeexport { ApiError };

This line exports the ApiError class so it can be imported and used in other parts of the application.

Conclusion

The ApiError class provides a structured way to handle API-related errors in JavaScript applications. By extending the built-in Error class, ApiError adds meaningful context and properties to errors, making them easier to handle and debug. Understanding and using custom error classes like ApiError can significantly enhance error management and overall code quality in your applications.