Skip to content

Instantly share code, notes, and snippets.

@AttilaGal
Last active June 19, 2018 14:35
Show Gist options
  • Save AttilaGal/fdf9c8269d63818ea0f8257fa932d51b to your computer and use it in GitHub Desktop.
Save AttilaGal/fdf9c8269d63818ea0f8257fa932d51b to your computer and use it in GitHub Desktop.
express tryCatch helper
************************************************************
the helper function
************************************************************
const tryCatch = (func) => (req, res, next) => {
try {
await func(req, res, next);
} catch (err) {
next(err);
}
};
************************************************************
controller file before tryCatch helper
************************************************************
function myEndpointA(req, res, next) {
try {
// endpoint A logic
} catch(err) {
next(err);
}
}
function myEndpointB(req, res, next) {
try {
// endpoint B logic
} catch(err) {
next(err);
}
}
function myEndpointC(req, res, next) {
try {
// endpoint C logic
} catch(err) {
next(err);
}
}
module.exports = {
myEndpointA,
myEndpointB,
myEndpointC
};
************************************************************
controller file after implementing tryCatch
************************************************************
const myEndpointA = tryCatch((req, res, next) {
// endpoint A logic
});
const myEndpointB = tryCatch((req, res, next) {
// endpoint B logic
});
const myEndpointC = tryCatch((req, res, next) {
// endpoint C logic
});
module.exports = {
myEndpointA,
myEndpointB,
myEndpointC
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment