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
-
Class Definition:
ApiErrorextends theErrorclass, which allows it to function as a standard error with added custom properties. This enables more structured error handling in API responses. -
Constructor Parameters:
statusCode: An HTTP status code, like404or500, 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.
-
Properties Set in Constructor:
super(message): Calls the parentErrorclass’s constructor withmessage, makingApiErroran instance ofError.this.statusCode: Stores the HTTP status code associated with this error.this.data: Initialized asnulland can hold additional information if needed.this.message: Stores the custom error message.this.success: Set tofalseto indicate that the API call failed.this.errors: Holds the array of additional error details.
-
Stack Trace Handling:
- If a
stackis provided, it’s assigned tothis.stack. - Otherwise,
Error.captureStackTraceis called, creating a detailed stack trace starting fromApiError’s instantiation. This helps developers trace where the error was created in the code.
- If a
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
-
Class Definition:
ApiResponsesis a class that wraps API response details into a single object, making it easy to manage and return responses in a structured way. -
Constructor Parameters:
statusCode: The HTTP status code (like200for success or404for 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.
-
Properties Set in Constructor:
-
this.statusCode: Stores the HTTP status code, defining whether the request was successful (usually below400). UsingstatusCode < 400is 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
ApiResponsesclass, settingthis.success = statusCode < 400means: -
- If
statusCodeis less than 400 (like 200 or 201), it’s treated as a successful response, sosuccessis set totrue. - If
statusCodeis 400 or above (like 404 or 500), it’s considered an error response, sosuccessis set tofalse.this.data: Holds the main data of the response.this.message: Provides a summary of the response, such as"Success"for successful requests or a custom message.this.success: Automatically set totrueifstatusCodeis less than400, meaning the response was successful. Otherwise, it’s set tofalse.
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:
- A
200status code indicates success. datacontains the fetched item details.- A message of
"Data fetched successfully"describes the response. successistruesince200 < 400.