Explain Error Handling in Express.js Using An Example (original) (raw)

**Error Handling is one of the most important parts of any web application development process. It ensures that when something goes wrong in your application, the error is caught, processed, and appropriately communicated to the user without causing the app to crash. In Express.js error handling, requires a proper understanding of how middleware and error-handling mechanisms work.

What is Error Handling in Express.js?

Error Handling in Express.js involves capturing and managing errors that occur during the processing of HTTP requests. This may involve validation errors, runtime errors, database connection issues, or other unexpected exceptions. Without proper error handling, these errors can lead to unhandled rejections, server crashes, or poor user experiences.

Express uses a middleware approach to handle errors, allowing you to define functions that catch and respond to errors throughout your application.

How Error Handling Works in Express.js?

Express.js handles errors through middleware functions, specifically error-handling middleware. A middleware in Express is a function that takes in a request (req), response (res), and the next function (next). In the case of error-handling middleware, it also takes in an additional err argument, making it look like this:

function errorHandler(err, req, res, next) {
// Handle the error
}

For Express to recognize a middleware as an error handler, it must have four parameters: err, req, res, and next. This middleware can be placed at any point in the request-response cycle but is often placed after route definitions to catch errors generated during request processing.

**Reason For Using Error Handling in Express.js

**Ways to Perform Error Handling

**1. **Middleware function

Express.js has built-in support for error-handling middleware, which allows you to handle errors that occur during the execution of the application.

**Syntax:

app.use(function(error, request, response, next) { // Handle the error response.status(500).send('Internal Server Error'); });

**2. Try-Catch statements

You can use try-catch statements to handle errors that occur within specific blocks of code. This ensures that any errors that occur are caught and handled in a controlled manner.

**Syntax:

app.get('/', function (req, res) { try { // Code that might throw an error } catch (error) { // Handle the error res.status(500).send('Internal Server Error'); } });

**3. Error logging

You can set up error logging so that any errors that occur during the execution of the application are logged to a file or a database for later analysis.

**Syntax:

app.get('/', function (req, res) {   try { throw new Error('Something went wrong'); } catch (error) { console.error(error); } });

**Error codes: You can set up error codes for different types of errors that occur during the execution of the application. This makes it easier to identify and handle specific errors.

**Example:

const fs = require('fs');

fs.readFile('nonexistent-file.txt', (error, data) => { if (error) { console.error(error.code); } else { console.log(data.toString()); } });

**4. **HTTP status codes

You can use HTTP status codes to indicate the type of error that occurred. For example, a status code of 400 (Bad Request) can indicate a validation error, while a status code of 500 (Internal Server Error) can indicate a server-side error.

**Syntax:

 const http = require('http');

const server = http.createServer((request, response) => { response.statusCode = 200; response.end('OK'); });

server.listen(8080);

Let's see some basic examples and explanations for Error Handling in Express.js:

**Example 1: Using a middleware function: You can use a middleware function to handle errors that occur during the execution of an application. The middleware function should have four arguments: error, request, response, and next.

JavaScript `

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

// Custom error handling middleware const errorHandler = (err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); };

app.use((req, res, next) => { throw new Error('Something broke!'); });

// Use the custom error handling middleware app.use(errorHandler);

app.listen(3000, () => { console.log('App is listening on port 3000'); });

`

**Steps to run the application: Write the below code in the terminal to run the application:

node index.js

**Output:

**Explanation:

**Example 2: Using the try-catch statement: You can use the try-catch statement to handle errors that occur within a specific block of code.

JavaScript `

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

app.get('/', (req, res, next) => { try { // Some code that might throw an error const data = someFunctionThatMightThrowError(); res.status(200).json( { message: 'Data retrieved successfully', data }); } catch (error) { next(error); } });

// Custom error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json( { message: 'Something went wrong!' }); });

app.listen(3000, () => { console.log('App is listening on port 3000'); });

`

**Explanation:

**Steps to run the application: Write the below code in the terminal to run the application:

node index.js

**Output:

**Explanation:

**Example 3: **Using the next() function: You can use the next() function to pass errors to the next middleware function in the chain.

JavaScript `

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

app.get('/', (req, res, next) => { // Some code that might throw an error const data = someFunctionThatMightThrowError(); if (!data) { return next(new Error('Error retrieving data')); } res.status(200).json( { message: 'Data retrieved successfully', data }); });

// Custom error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json( { message: 'Something went wrong!' }); });

app.listen(3000, () => { console.log('App is listening on port 3000'); });

`

**Explanation:

**Steps to run the application: Write the below code in the terminal to run the application:

node index.js

Here's an example using curl:

curl http://localhost:3000

**Output: