,

Express JS – 3 – Middleware Express, Gestion des Erreurs – Guide Complet

Posted by


In this tutorial, we will cover middleware in Express JS and how to handle errors in a Node.js application using Express. Express is a web application framework for Node.js that allows you to build powerful and efficient server-side applications. Middleware in Express is a function that has access to the request and response objects, as well as the next middleware function in the application’s request-response cycle.

Middleware functions can be used for various purposes, such as authentication, logging, error handling, and data parsing. They can be added to the application using the app.use() method, where you can pass a function that will be executed for every request that the server receives.

To demonstrate middleware in Express, let’s create a simple server that logs the time of each request. First, you need to install Express by running npm install express in your terminal. Then, create a new file called app.js and add the following code:

const express = require('express');
const app = express();

// Custom middleware function
const logger = (req, res, next) => {
  console.log(`Time: ${new Date().toLocaleString()}`);
  next();
};

// Use the logger middleware for all requests
app.use(logger);

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});

In this code, we define a custom middleware function called logger that logs the current time to the console. We then use the app.use() method to apply the logger middleware to all incoming requests. When you run the server using node app.js and visit http://localhost:3000 in your browser, you should see the time logged to the console for each request.

Next, let’s talk about error handling in Express. In a Node.js application, errors can occur for various reasons, such as invalid user input, database failures, or external API issues. Express provides a way to handle errors using middleware functions specifically designed for error handling.

To handle errors in Express, you can create an error-handling middleware function that takes four arguments: err, req, res, and next. This middleware function should be defined as the last middleware in your application, after all other routes and middleware functions.

Here’s an example of an error-handling middleware function in Express:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

In this code, we define an error-handling middleware function that logs the error stack trace to the console and sends a generic error message with a status code of 500 to the client. You can customize this function to suit your application’s error-handling requirements.

To trigger an error in your Express application, you can throw an error inside a route handler or middleware function. For example:

app.get('/error', (req, res, next) => {
  const err = new Error('Custom error message');
  next(err);
});

This route handler throws a custom error with a message of “Custom error message” when the client requests the /error endpoint. The error is then passed to the error-handling middleware function we defined earlier, which logs the error and sends a response to the client with a status code of 500 and an error message.

In conclusion, middleware in Express allows you to extend the functionality of your application by adding custom functions that can be executed for every request. Error handling in Express enables you to handle errors gracefully and provide meaningful error messages to clients. By understanding and using middleware and error handling in Express, you can create robust and reliable Node.js applications.