9.ErrorHandling

Error handling in Express

We can get two types of errors:

  • Operational Errors
  • Programming Errors

Operational Errors

Problem that we can predict will happen at some point, so we just need to handle them in advance.

Operational Errors have nothing to do with bugs in code, instead they depend on the user or system or network.

Examples:

  • Invalid path accessed.
  • Invalid user input(validator error from mongoose).
  • Failed to connect to server.
  • Failed to connect to database.
  • Request timeout.

Programming Errors

Bugs that we developers introduce into our code. Difficult to find and handle.

Examples:

  • Reading properties on undefined.
  • Passing a number where an object is expected.
  • Using await without async.
  • Using req.query instead of req.body.

In Express, we will handle operational errors with one central error handling middleware, which can handle errors coming from all over the application.
Handling means sending a response, letting the user know what happened.