Error handling with ExpressJS

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don’t need to write your own to get started.

It’s important to ensure that Express catches all the errors that occur while running route handlers and middleware.

app.get('/', function (req, res, next) {
  fs.readFile('/file-does-not-exist', function (err, data) {
    if (err) {
      next(err) 
    } else {
      res.send(data)
    }
  })
})

If you pass anything to the next() function (except the string ‘route’), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.

If the callback in a sequence provides no data, only errors, you can simplify this code as follows:

app.get('/', [
  function (req, res, next) {
    fs.writeFile('/inaccessible-path', 'data', next)
  },
  function (req, res) {
    res.send('OK')
  }
])

You can read more about Error Handling on this link.

You can also read this

The :valid CSS pseudo-class

The :valid CSS pseudo-class represents any  <input> or other <form> element whose...

input:valid {
  background-color: powderblue;
}

How to apply single quotes around every value using VS code?

I often work with large documents and very often I...

'Nick',
'Ivan'