Skip to content

Instantly share code, notes, and snippets.

@tudorilisoi
Last active January 21, 2020 17:39
Show Gist options
  • Save tudorilisoi/92d1723baf2f0d85769424330c42177e to your computer and use it in GitHub Desktop.
Save tudorilisoi/92d1723baf2f0d85769424330c42177e to your computer and use it in GitHub Desktop.
// this wraps an async express route handler function into a try-catch
// it returns a new function which handles failures gracefully
// by sending a JSON encoded message and a HTTP 500 (internal server error) status code
function expressTryCatchWrapper(requestHandler) {
return async function (req, resp, next) {
try {
await requestHandler(req, resp, next)
} catch (ex) {
console.error(`expressTryCatch ERROR ${req.url}`, ex)
if (resp.headersSent) {
console.log(`**** HEADERS SENT ****`)
return
}
return resp.status(500).json({
message,
info: ex.toString()
})
}
}
}
export { expressTryCatchWrapper }
//async await
//wrapping route handlers
const getPostContactInfo =async (req, res) => {
try{
const data = await databaseFetch()
return resp.status(200).send({data})
}
catch(e){
return resp.status(500).json({
message,
info: ex.toString()
})
}
}
const getPostContactInfo = expressTryCatchWrapper(async (req, res) => {
if(Math.random()<0.5){
res.json({ email, phone })
}else{
throw new Error(`Bummer!`)
}
})
app.get('/', getPostContactInfo )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment