Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

next(error) skipping middlewares #51

Open
brijeshhroy opened this issue Mar 18, 2023 · 2 comments
Open

next(error) skipping middlewares #51

brijeshhroy opened this issue Mar 18, 2023 · 2 comments

Comments

@brijeshhroy
Copy link

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
Copy link

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
Copy link

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants