6

I'm learning Express.js and using their generator I generated a new app with:

npm install express-generator -g && express myapp

After that I saw in app.js that there is this code:

// catch 404 and forward to error handler
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");
});

enter image description here

As you can see in the image eslint is complaining about next parameter, declared and never used. I agree, but if I remove it express doesn't render the error page.

Why this behavior?

This is dangerous for me because I can't trust anymore eslint or my coding degree? I'm surely missing something. But what?

Fred Hors
  • 3,258
  • 3
  • 25
  • 71
  • Possible duplicate of [What is the parameter "next" used for in Express?](https://stackoverflow.com/questions/10695629/what-is-the-parameter-next-used-for-in-express) – OtterJesus Aug 13 '18 at 16:31

4 Answers4

4

Because the error handler in express is determined by the number of parameters:

  (function (req, res, next) { }).length // 3
  (function (err, req, res, next) {}).length // 4
  (function (err, req, res) {}).length // 3

therefore if you remove the parameter the error handler won't be treated as an error handler anymore.

This is dangerous for me because I can't trust anymore eslint or my coding degree?

If linters would understand the code better than a programmer ... why would we need programmers?

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
3

This is known issue with ESlint and yet they still did not solve that issue. ESlint does not give error if one of the res, req is not used but gives in error handler where you are required to have 4 arguments. There are 2 solutions, one is to disable ESlint for the next line for this error like so:

// eslint-disable-next-line no-unused-vars
app.use((error, req, res, next) => {

and another one i to just use next() at the end of the error handler which will never be executed after you either render or send json when error occurs.

0

next() is necessary for handling async errors. Add:

  if (err) {
     next(err);
  }
justMe
  • 674
  • 7
  • 26
0

Eslint requires you to use all the parameters that are passed to the function.

For your case you have two options, execute next () at the end of your function or include this same function among eslint comments:

/ * eslint-disable * / / * eslint-enable * /

Henrique Viana
  • 645
  • 4
  • 12