Last active
June 19, 2018 14:35
-
-
Save AttilaGal/fdf9c8269d63818ea0f8257fa932d51b to your computer and use it in GitHub Desktop.
express tryCatch helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
************************************************************ | |
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