This function asyncHandler
is a higher-order function that takes another function requestHandler
as an argument. It returns a new function that handles asynchronous operations within Express.js middleware.
Here's how it works:
requestHandler
as an argument, which is a function that handles a request, response, and next middleware function.req
, res
, and next
as arguments (typical Express.js middleware signature).Promise.resolve()
is used to ensure that the requestHandler
function always returns a promise. This is important for handling both synchronous and asynchronous code.requestHandler
function is called with req
, res
, and next
arguments, and its return value (which is expected to be a promise) is handled by Promise.resolve()
..then()
chain doesn't do anything because there's no additional logic specified. If it fails (i.e., the promise is rejected), .catch()
is triggered, and it passes the error to the next()
function, which sends it to Express's error handling middleware.
src\\utils\\asyncHandler.js
const asyncHandler = (requestHandler) => {
return (req, res, next) => {
Promise.resolve(requestHandler(req, res, next)).catch((err) => next(err))
}
}
export {asyncHandler}
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}
**src\\utils\\ApiResponse.js**
class ApiResponse {
constructor(statusCode, data, message = "Success"){
this.statusCode = statusCode
this.data = data
this.message = message
this.success = statusCode < 400
}
}