Created
May 24, 2021 13:53
-
-
Save calvin-puram/1133d6e85152aa2c0972600221940ec3 to your computer and use it in GitHub Desktop.
set global error wrapper
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
objective: we want to remove the duplicates error we have in our routes i.e in the catch block of every route since they are all thesame we want to create a middleware that will dirrect such errors directely to our global error handler | |
steps: | |
1 create a new file may in your utils folder and called it anything | |
2 we will use this code snippet which is just a middleware that resolve a promise | |
module.exports = fn => { | |
return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); | |
}; | |
3 next we will import this into all our routes and use it like this: | |
const catchAsync = require('../utils/catchAsync'); | |
3a remove the try and catch you have in all the routes and have something like this | |
exports.signup = catchAsync(async (req, res, next) => { | |
const user = await Users.create(req.body); | |
// this here can be any error but we remove the error in the catch block completely because this middleware will do the work for us | |
sendToken(user, res, 201); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment