Skip to content

Instantly share code, notes, and snippets.

@frankfaustino
Last active May 5, 2018 04:24
Show Gist options
  • Save frankfaustino/937ee55ee36d799671bd66118442ac97 to your computer and use it in GitHub Desktop.
Save frankfaustino/937ee55ee36d799671bd66118442ac97 to your computer and use it in GitHub Desktop.
Error handling async await in an Express server 🤖
const express = require('express')
const db = require('./data/helpers/tagDb')
const server = express()
server.use(express.json())
// Catches async/await errors/Promise rejections and passes it along to express middleware
const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next)
// Error Handler (displays full error details)
const handleErrors = (err, req, res, next) => {
const errorDetails = {
status: err.status,
message: err.message,
stack: err.stack || ''
}
res.status(err.status || 500).json(errorDetails)
}
// Route using async/await. No need for try/catch since our function is wrapped with catchErrors function
async postTag(req, res) => {
const response = await db.insert() // Will fail call to database
res.json(response)
}
// Wrap postTag with catchErrors
server.post('/api/tags', catchErrors(postTag))
// Make sure we pass handleErrors function as Middleware
server.use(handleErrors)
server.listen(8080, () => console.log('Hey from port 8080!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment