You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
16 Hrs
12 Min
14 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Middlewares - ErrorHandler

14/30
Resources

Error handling is a critical aspect of developing robust web applications. Well-implemented error handling middleware can make the difference between a frustrating user experience and one that clearly communicates what is happening, while providing developers with the information they need to troubleshoot problems. In this article, we will explore how to create effective error handling middleware for Node.js applications.

How to create an error handling middleware for Node.js?

Error handling is crucial in any application. When working with APIs and servers, we need to properly catch and handle errors that may arise during database connections, internal API calls or any other operation that may go wrong. Good error handling middleware allows us to present useful information to both developers and end users.

To begin, we will create a file called errorHandle.js inside our middleware folder:

const errorHandle = (error, req, res, next) => { // Determine the error status code const statusCode = error.statusCode || 500;  
 // Prepare the error message const message = error.message || "An unexpected error occurred";  
 // Log the error to the console for debugging console.error(`There wasan error: ${new Date().toISOString()} ${statusCode} ${message}`);  
 // If there is stack trace, we also log it if (error.stack) { console.error(error.stack); }  
 // Unstructure Node environment const { NODE_ENV } = process.env;  
 // Send JSON response with error res.status(statusCode).json({ status: "error", statusCode, message, // Include additional details only in development mode...(NODE_ENV === "development" && { stack: error.stack }) }) };}; };
module.exports = errorHandle;

This middleware receives four parameters:

  • The error object
  • The request
  • The response (response)
  • The next function to continue the flow

How to configure the environment variables for error handling?

An important aspect of our middleware is that it displays different levels of detail depending on the environment in which the application is running. For this, we use the NODE_ENV environment variable, which can have the following values:

  • development: shows detailed information about the error, including the stack trace.
  • production: Displays only basic information, hiding technical details from users.
  • staging: An intermediate environment for testing

To set this variable, we can create an .env or .env.example file:

NODE_ENV=development

It is a good practice to include an .env.example file in our repository with the necessary fields but without sensitive values, so that other developers know which variables they need to set.

How to integrate the error middleware in our application?

Once our middleware is created, we must integrate it into our main application:

const errorHandle = require('./middleware/errorHandle');
// Other middleware and configurations...
// Integrate the error handling middlewareapp.use(errorHandle);
// Test path to simulate an errorapp.get('/error', (req, res, next) => { next(new Error("Intentional error"));});

It is important to note that the error handling middleware must register after all routes and other middleware, as it must catch any errors that occur anywhere in the application.

How to test our error handling middleware?

To test our middleware, we have created a specific route that generates an error intentionally. We can access this path from the browser or by using tools such as Postman:

Behavior in development mode.

When NODE_ENV=development, the response will include:

  • Status code (500)
  • Error message ("Intentional Error")
  • Stack trace complete

In the server console, we will see detailed information about the error, including:

  • Date and time
  • Status code
  • Error message
  • Complete stack trace

Behavior in production mode

When NODE_ENV=production, the response to the client will be more limited:

  • Status code (500)
  • Generic message ("Internal Server Error")
  • No stack trace

However, in the server console we will still see the complete error information, which allows us to debug problems without exposing technical details to users.

Why is it important to differentiate between development and production environments?

Differentiating between environments is crucial for security and user experience. In development, we need as much information as possible to identify and fix problems quickly. In production, we need to protect sensitive information and provide friendly error messages.

Some benefits of this approach:

  • Improved security: We do not expose implementation details or potential vulnerabilities.
  • Improved user experience: Error messages are clear and non-technical.
  • Ease of debugging: Developers still have access to detailed information in the server's logs

Implementing robust error handling middleware is a fundamental step in creating professional and reliable web applications. With the code and explanations provided, you now have the tools to implement your own error handling system tailored to the specific needs of your application.

Have you implemented error handling systems in your projects? What additional strategies do you use to make your applications more robust? Share your experiences in the comments.

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Para crear un middleware que maneje errores en Express, sigue estos pasos: 1. **Definir la funci贸n del middleware**: Crea una funci贸n que reciba `error`, `req`, `res`, y `next`. 2. **Obtener el status code**: Extrae `error.statusCode` o asigna 500 como valor por defecto. 3. **Preparar el mensaje**: Captura `error.message` o usa un mensaje por defecto como "Ocurri贸 un error inesperado". 4. **Loggear el error**: Utiliza `console.error` para registrar detalles del error. 5. **Enviar respuesta**: Responde con `res.status(statusCode).json({ status: 'error', message, stack: process.env.NODE_ENV === 'development' ? error.stack : undefined })`. 6. **Integrar el middleware**: Usa `app.use(middlewareFunction)` despu茅s de definir tus rutas. Esto te dar谩 un manejo centralizado de errores en tu API.