asyncHandler Function:
const asyncHandler = (fn) =>
function handleAsync(...args) {
const fnResult = fn(...args);
const callback = args[args.length - 1];
return Promise.resolve(fnResult).catch(callback);
};
export default asyncHandler;
ErrorHandling Class:
class ErrorHandling extends Error {
constructor(message, errorCode) {
super(message);
this.errorCode = errorCode;
this.status = `${errorCode}`.startsWith('4') ? 'fail' : 'error';
this.isHandled = true;
Error.captureStackTrace(this, this.constructor);
}
}
export default ErrorHandling;
DataController Code:
const dataController = asyncHandler(async (req, res, next) => {
const { infoTitle, information } = req.body;
if (!infoTitle || !information) {
return next(new ErrorHandling('All fields are mandatory', 400));
}
const dataDocument = await Data.create(req.body);
return res.status(201).json({
status: 'success',
dataDocument
});
});
export default dataController;
Routing Code:
router.route('/data').post(dataController);