I don't understand error handling middlewares (Express)

I'm learning from fullstackopen.com and now I'm going into error handling middlewares.

This is their demo code for this part : https://github.com/fullstack-hy2020/part3-notes-backend/blob/part3-5/index.js

My understanding is that middlewares need to have next() for the next middleware to be executed. Why the demo code shows ...

const errorHandler = (error, request, response, next) => {
  console.error(error.message)

  if (error.name === 'CastError') {
    return response.status(400).send({ error: 'malformatted id' })
  }

  next(error)
}

const unknownEndpoint = (request, response) => {
  response.status(404).send({ error: 'unknown endpoint' })
}

app.use(unknownEndpoint)
app.use(errorHandler)


while there's no next() in unknownEndpoint middleware. How can errorHandler middleware be executed then?
GitHub
Contribute to fullstack-hy2020/part3-notes-backend development by creating an account on GitHub.
part3-notes-backend/index.js at part3-5 · fullstack-hy2020/part3-no...
Was this page helpful?