Introducci贸n a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas din谩micas
Body parser
Postman
CRUD
驴Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Soluci贸n del reto de validaci贸n
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticaci贸n utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creaci贸n y Migraci贸n de Modelos con Prisma para Citas M茅dicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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:
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 testingTo 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.
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.
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:
When NODE_ENV=development
, the response will include:
In the server console, we will see detailed information about the error, including:
When NODE_ENV=production
, the response to the client will be more limited:
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.
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:
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
Want to see more contributions, questions and answers from the community?