2. Custom Api and error handeling

1.API Error Handling

The ApiError class is a custom error class extending the built-in Error class in JavaScript.
This class is designed to handle errors in an organized way within an API application, providing extra details like HTTP status codes, error messages, and specific error details.

Code Structure and Explanation

src/utils/ApiError.js

class 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 };

Explanation

  1. Class Definition: ApiError extends the Error class, which allows it to function as a standard error with added custom properties. This enables more structured error handling in API responses.

  2. Constructor Parameters:

    • statusCode: An HTTP status code, like 404 or 500, representing the error type.
    • message: A custom message describing the error. Defaults to "Something went wrong".
    • errors: An array holding additional details about the error, such as validation issues.
    • stack: An optional parameter for a custom stack trace, which helps locate where the error occurred in the code.
  3. Properties Set in Constructor:

    • super(message): Calls the parent Error class’s constructor with message, making ApiError an instance of Error.
    • this.statusCode: Stores the HTTP status code associated with this error.
    • this.data: Initialized as null and can hold additional information if needed.
    • this.message: Stores the custom error message.
    • this.success: Set to false to indicate that the API call failed.
    • this.errors: Holds the array of additional error details.
  4. Stack Trace Handling:

    • If a stack is provided, it’s assigned to this.stack.
    • Otherwise, Error.captureStackTrace is called, creating a detailed stack trace starting from ApiError’s instantiation. This helps developers trace where the error was created in the code.

Usage Example

Here’s how you might use ApiError in an API route:

app.get('/some-endpoint', (req, res, next) => {
    try {
        // Code that might throw an error
        throw new ApiError(404, "Resource not found", ["Missing item"], "");
    } catch (error) {
        next(error); // Passes the error to error-handling middleware
    }
});

In this example, an ApiError with a 404 status code and a specific error message is thrown, along with error details (["Missing item"]). This error can be caught by error-handling middleware, which will format it for the client.


2. API Response Handling

The ApiResponses class is designed to create standardized responses for API endpoints. This setup provides consistency and clarity when sending responses from an API.

Code Structure and Explanation

src/utils/ApiError.js

class ApiResponses {
    constructor(statusCode, data, message = "Success") {
        this.statusCode = statusCode;
        this.data = data;
        this.message = message;
        this.success = statusCode < 400;
    }
}

export { ApiResponses };

Explanation

  1. Class Definition: ApiResponses is a class that wraps API response details into a single object, making it easy to manage and return responses in a structured way.

  2. Constructor Parameters:

    • statusCode: The HTTP status code (like 200 for success or 404 for not found) that indicates the outcome of the API request.
    • data: The main content of the response, such as data fetched from the database or created as a result of the request.
    • message: A message summarizing the response. It defaults to "Success" but can be customized for various responses.
  3. Properties Set in Constructor:

    • this.statusCode: Stores the HTTP status code, defining whether the request was successful (usually below 400). Using statusCode < 400 is a way to check if an API response is successful or not. In HTTP, status codes are categorized as follows:

    • 2xx: Success responses (e.g., 200 OK, 201 Created)

    • 3xx: Redirection responses (e.g., 301 Moved Permanently)

    • 4xx: Client errors (e.g., 400 Bad Request, 404 Not Found)

    • 5xx: Server errors (e.g., 500 Internal Server Error)

    In the ApiResponses class, setting this.success = statusCode < 400 means:

Usage Example

This example shows how to use the ApiResponses class to return a standardized response from an API endpoint:

app.get('/some-endpoint', (req, res) => {
    const data = { id: 1, name: "Sample Item" };
    const response = new ApiResponses(200, data, "Data fetched successfully");
    res.json(response);
});

In this example: