Last active
August 5, 2021 12:17
-
-
Save WLun001/62c31dc7c700b64cd08d680e5b4e6fb8 to your computer and use it in GitHub Desktop.
express error handling
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
const express = require('express'); | |
const app = express(); | |
// cookie parser | |
// body parser | |
// cors | |
// if applicable | |
app.use('/api/user', userRoute(express.Router())) | |
// error handling | |
app.use((err, req, res, next) => { | |
// log error | |
if (err instanceof MyError) { | |
res.status(err.statusCode).json(err.message); | |
} else { | |
res.status(500).json(err); | |
} | |
return next(); | |
}) | |
// another file | |
const asyncHandler = fn => (...args) => { | |
const fnReturn = fn(...args); | |
const next = args[args.length - 1]; | |
return Promise.resolve(fnReturn).catch(next); | |
}; | |
module.exports = (router) => { | |
router.route('/:id').get(asyncHandler(getUser)) | |
} | |
const getUser = async function (req, res) { | |
const { id } = req.param; | |
if (!id) throw new Error('if has error.'); | |
const user = await dbCall(); | |
res.status(200).json({ user }); | |
}; | |
Author
WLun001
commented
Aug 5, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment