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)
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
part3-notes-backend/index.js at part3-5 · fullstack-hy2020/part3-no...
Contribute to fullstack-hy2020/part3-notes-backend development by creating an account on GitHub.
3 Replies
Joao
Joao2y ago
I see in their site that there's a Discord support group, perhaps that's the better place to ask: https://fullstackopen.com/en/about
About the course | Full Stack open
Open online course on JavaScript based modern web development by University of Helsinki and Houston Inc..
Joao
Joao2y ago
However, unkownEndpoint is not meant as an error handler. Error handler routes in express are the ones that have 4 arguments, so unknown endpoint would only ever be called when making a request to your server that is not handled by any route. An error is when you explicitly call next(error) somewhere in the routes, or something unexpected happens. For example here:
app.get('/api/notes');
app.get('/api/notes');
If you make a request to /api/whatever which your server doesn't know how to handle, it will eventually run into the unknownEndpoing middleware and use that, as a catch-all route handler.
meku
mekuOP2y ago
I see, I think I understand it now. Thanks!
Want results from more Discord servers?
Add your server