Skip to content

Instantly share code, notes, and snippets.

@garenyondem
Created June 15, 2020 18:52
Show Gist options
  • Save garenyondem/37f7202a48e13171463e414638cfc94f to your computer and use it in GitHub Desktop.
Save garenyondem/37f7202a48e13171463e414638cfc94f to your computer and use it in GitHub Desktop.
Async handler, wrapers, error handlers
exports.errorHandler = (response, err) => {
const statusCode = err.status || 500;
response.status(statusCode).json({
success: false,
error: err.message
});
};
exports.successHandler = (response, data) => {
response.json({
success: true,
data
});
};
exports.asyncHandler = fn => {
return async function(request, response) {
try {
const data = await fn(request, response);
exports.successHandler(response, data);
} catch (err) {
exports.errorHandler(response, err);
}
};
};
exports.asyncNextHandler = fn => {
return async function(request, response, next) {
try {
await fn(request, response, next);
next();
} catch (err) {
exports.errorHandler(response, err);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment