Reputation: 563
the first .catch statement doesn't catch because if the wrong task_id is entered the returned value is null and not an error. Can someone show me how to properly handle this error?
router.get("/tasks/:task_id", passport.authenticate('jwt', { session: false }), (req, res) => {
(User.findById(req.user.id)
.then(user => res.json(user.tasks.id(req.params.task_id)))
.catch(err => res.status(404).send({ tasknotfound: "No matching task found" }))
).catch(err =>
res.status(404).json({ usernotfound: "No user found" })
)})
Upvotes: 1
Views: 108
Reputation: 7822
So when we hit this route, first we use our middleware to ensure authentication is in place, right? After that, we have our callback, etc ...
So what I like to do here (we're talking about the error handling)is to make an empathy error array. Afterward, I do make checks. Here we're checking if there's a username and a task present in our reg.body
and if there's something missing, we push an object with the custom error messages. After that, we check if the errors array is greater than 0 and if it is we render those error(s). On the other hand, if everything went well what we want to do is use that data, assign it to an object, save it to our DB, show the user a success message of some sorts, and potentially redirect the user to an appropriate route. Task
would be a Mongoose model
. I used the Express router
approach, and that ensureAuthenticated
is just a middleware name I gave. Passport.js
that you're using is awesome. I wrote this by following your code and show you how I would do it. Sidenote: I usually use connect-flash for displaying my success/ error messages.
npm install connect-flash
router.post('/', ensureAuthenticated, (req, res) => {
let errors = [];
if(!req.body.username){
errors.push({text:'Please add a username'});
}
if(!req.body.task){
errors.push({text:'Please add some tasks'});
}
if(errors.length > 0){
res.render('/add', {
errors: errors,
title: req.body.username,
details: req.body.tasks
});
} else {
const newTask = {
username: req.body.username,
tasks: req.body.tasks,
id: req.user.id
}
new Task(newTask)
.save()
.then(task => {
req.flash('success_msg', 'Your task has been added');
res.redirect('/tasks');
})
}
});
Upvotes: 1
Reputation: 563
It's difficult to read but it works, searches for subdocs directly returns an array of objects, then in the .then
statement return a JSON of the first object in the array, this way if the id doesn't exist it will actually throw an err to be caught.
router.get("/tasks/:task_id", passport.authenticate('jwt', { session: false }), (req, res) => {
(User.findOne({ "tasks._id": req.params.task_id }, { "tasks.$": 1 })
.then(task =>res.json(task.tasks[0]))
.catch(err => res.status(404).send({ tasknotfound: "No matching task found" }))
)
.catch(err =>
res.status(404).json({ usernotfound: "No user found" })
)
})
Upvotes: 0