Skip to content

Instantly share code, notes, and snippets.

@WLun001
Last active August 5, 2021 12:17
Show Gist options
  • Save WLun001/62c31dc7c700b64cd08d680e5b4e6fb8 to your computer and use it in GitHub Desktop.
Save WLun001/62c31dc7c700b64cd08d680e5b4e6fb8 to your computer and use it in GitHub Desktop.
express error handling
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 });
};
@WLun001
Copy link
Author

WLun001 commented Aug 5, 2021

export class MyError extends Error {
  constructor(
    public messages
    public statusCode = 500,
  ) {
    super(message);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment