Last active
May 5, 2018 04:24
-
-
Save frankfaustino/937ee55ee36d799671bd66118442ac97 to your computer and use it in GitHub Desktop.
Error handling async await in an Express server 🤖
This file contains 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
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