[Express] Can someone explain me this code?

I had just started working on the excersise tracker project
and I found this code from github template which I don’t understand what it does and how

// Not found middleware
app.use((req, res, next) => {
  return next({status: 404, message: 'not found'})
})

// Error Handling middleware
app.use((err, req, res, next) => {
  let errCode, errMessage

  if (err.errors) {
    // mongoose validation error
    errCode = 400 // bad request
    const keys = Object.keys(err.errors)
    // report the first validation error
    errMessage = err.errors[keys[0]].message
  } else {
    // generic or custom error
    errCode = err.status || 500
    errMessage = err.message || 'Internal Server Error'
  }
  res.status(errCode).type('txt')
    .send(errMessage)
})
// Not found middleware

This gets called if none of the previous handlers handled request and sent a response (so called catch all handler).

// Error Handling middleware

This is a special middleware with four parameters and it gets called if any of the previous handlers (regular or middleware) throws an error.

1 Like

So I have to put my all handlers before this code and when none of my handlers handle request (in case of error) this code shows error right?

Correct.

Not quite.
If there is no handler for your request then “Not found middleware” will be called.
“Error handling middleware” will be called if any of the previous handlers will throw an error (including “Not found middleware”).

1 Like

Thanks, after reading your answer and docs now I get everything.