john-smilga / node-express-course

3.6k stars 3.79k forks source link

next(error) skipping middlewares #51

Open brijeshhroy opened 1 year ago

brijeshhroy commented 1 year ago

In the project of task-manager , this is the source-code in middleware/async.js

const asyncWrapper = (fn) => {
  return async (req, res, next) => {
    try {
      await fn(req, res, next)
    } catch (error) {
      next(error)              // Line ABC
    }
  }
}

module.exports = asyncWrapper

And this is the code in app.js

const express = require('express');
const app = express();
const tasks = require('./routes/tasks');
const connectDB = require('./db/connect');
require('dotenv').config();
const notFound = require('./middleware/not-found');
const errorHandlerMiddleware = require('./middleware/error-handler');

// middleware

app.use(express.static('./public'));
app.use(express.json());

// routes

app.use('/api/v1/tasks', tasks);

app.use(notFound);
app.use(errorHandlerMiddleware);
const port = process.env.PORT || 5000;

const start = async () => {
  try {
    await connectDB(process.env.MONGO_URI);
    app.listen(port, () =>
      console.log(`Server is listening on port ${port}...`)
    );
  } catch (error) {
    console.log(error);
  }
};

start();

Now the line ABC deom async.js shall execute app.use(notFound) , but instead it executes app.use(errorHandlerMiddleWare). Why is it so ?

AkmDgreat commented 1 year ago

this webpage states: "For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them" So, I guess when we call next(), we are passing the error to express I am not 100% sure

Harsh-2909 commented 1 year ago

@brijeshhroy the next(error) will pass the error to the express error handling middleware and as we have a custom errorHandler as a middleware, the error will be passed there. This is how it is intended. Now what happens here is that when the code runs next(error), the control will indeed go to notFound but notFound only takes 2 arguments (req, res) and based on the express error handling docs, an exception handler needs to accept err in the function argument. Thus the control will skip notFound and go to the errorHandlerMiddleware.

I hope i was able to explain it clearly and help you solve your doubts.