Q:

How to handle invalid routes from two files

I am trying to resolve a scenario where I want to catch invalid routes and throw a message in Node.
I have two files, one User file and one Task file. If I hit an endpoint/route that does not exist, I want to throw a message to the screen that says it is an invalid route. 
My question is that I specifically added a piece of code that catches these invalid routes in both files, user.js and task.js, but when I search for a valid request in the second route (task.js) I am getting an invalid route error from the first file (user.js). This is the code that I have in both files at the end of each file:
//handles invalid route requests (in user.js file)
router.get('*', (req, res) => {
    return res.status(404).send({error: 'Route not found'})
})

//handles invalid route requests (in task.js file)
router.all('*',(req, res) => {
    return res.status(404).json({error: 'Route not found'})
})

Is the solution to have this piece of code in only one of the route files? For example, should this code only be present in the task.js file so that it can check both route files until it reaches the invalid route case?

A:

So you're using express-js... I used to use it in generating in seleton with the express-skeleton module...
As you can see in the github page, the architecture of the app.js file is to call all your routing and after the errors routes. Please take a look here
At the end of your app.js :
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

