Chuck's Academy

Express JS

Error Handling and Logging in Express

A fundamental part of web application development is properly handling errors and logging important events, such as requests and responses. This not only helps maintain application stability but also facilitates debugging and monitoring. In this chapter, we will see how to efficiently handle errors and how to set up a logging system in Express.

Error Handling in Express

Errors can occur anywhere in an application, whether due to malformed requests, database issues, or logical errors. Express allows defining specific middleware for error handling that captures and processes these issues.

Error Handling Middleware

An error handling middleware is defined similarly to other middleware, but it accepts four arguments: err, req, res, and next. This middleware can capture any error that occurs in the application.

javascript
"This middleware captures any error that occurs in the application. It prints the error to the console with console dot error and then sends a response with a status code five hundred indicating that something went wrong."

Handling Asynchronous Errors

In modern applications, many operations are asynchronous. Express can handle asynchronous errors using try-catch blocks and the next method to pass control to the error handling middleware.

javascript
"In this example, we simulate an asynchronous error within a get route. The error is captured with a try-catch block and passed to the error handling middleware using next."

Defining Custom Errors

We can define our own custom errors to make error handling more detailed and specific. For example, we can create a custom error class and use it in our routes.

javascript
"We create a custom error class named NotFoundError that extends the Error class. This class includes a status code four zero four to indicate the resource was not found. If a user is not found in the route, we pass this error to the error handling middleware."

Setting Up Logging in Express

Logging is a key practice for recording application behavior, requests, responses, and significant events. A good logging system helps identify problems quickly and improves the ability to monitor an application in production.

Using Morgan for HTTP Request Logging

Morgan is a popular middleware for HTTP request logging in Express applications. It allows us to log information about each request that comes to the server, such as HTTP method, URL, and response status.

Installing Morgan

To use Morgan, we first install it in our project:

bash
"We install Morgan with the command npm install morgan to log HTTP requests in our application."

Configuring Morgan

We can configure Morgan to log requests in the console or in a log file. Below is an example of how to configure it to log requests in the console:

javascript
"Here we are using Morgan with the combined format, which is one of the most detailed log formats. Morgan logs information like request method, URL, status code, and response time."

If we want to log the logs into a file, we can do it by combining Morgan with Node.js's fs module:

javascript
"In this example, we're creating a write stream with fs dot createWriteStream to log requests to a file named access dot log. Morgan is configured to use this stream instead of the console."

Using Winston for Custom Logging

If we need a more advanced logging system, we can use Winston, a powerful library that allows us to create different log levels and send logs to multiple destinations (console, files, or external services).

Installing Winston

First, we install Winston:

bash
"We install Winston with the command npm install winston to create a more advanced logging system."

Configuring Winston

Next, let's see how to configure Winston to log both to the console and a file:

javascript
"Here we create a logger with winston dot createLogger. We set the log level to info and the format to JSON. We use two transport targets, the console and a file named app dot log. Then we log two messages, one of type info and another of type error."

Best Practices in Error Handling and Logging

  1. Do Not Expose Detailed Errors in Production: In production, it's important not to expose error details to end users, as this can compromise security. A generic message should be returned, and error details logged internally.
  2. Use Log Levels: Configuring log levels (info, error, warn, etc.) allows filtering what information is most important in a given context, such as in a development environment versus a production one.
  3. Monitor Logs in Production: In production applications, it is useful to monitor logs automatically using tools like PM2 or cloud monitoring services.

Conclusion

In this chapter, we learned how to handle errors in Express and set up a logging system using Morgan and Winston. Good error handling and an efficient logging system are essential to ensure the stability and security of a web application.


Ask me anything