Open In App

How to create Custom Error Handler middleware in Express ?

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Error handling is one of the crucial part while building applications. In Express JS middleware functions can be used to handle errors effectively. In this article, we will learn How to create custom error-handling middleware in Express.

Prerequisites:

Approach to create Custom Error Handler:

  • The first middleware simulates an error by throwing an exception.
  • The second middleware is the custom error handling middleware, which takes four parameters (err, req, res, next).
  • Extend the “Error” class to create a custom error class.
  • Place the error-handling middleware at the end of the stack.
  • Inside the custom error handling middleware, log the error, check its type, and send an appropriate response based on the you defined.

Syntax to create Custom Error Handler Middleware:

class MyCustomError extends Error {  
constructor(message) {
super(message);
this.name = 'MyCustomError';
}
}

Steps to Create Express application:

Step 1: In this, create the new folder by using the below command in the terminal.

mkdir folder-name
cd folder-name

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now, we will install the express dependency for our project using the below command.

npm install express

Folder Structure:

express-folder1

Folder Structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^4.18.2"
}

Example: Implementation of above approach.

Javascript




// index.js
 
const express = require('express');
 
const app = express();
 
// class of custom error
class MyCustomError extends Error {
    constructor(message) {
        super(message);
        this.name = 'MyCustomError';
    }
}
// Error handler function
const errorHandler = (err, req, res, next) => {
    console.error(err.stack);
 
    if (err instanceof MyCustomError) {
        return res.status(500).json({
                   error: 'Custom Error: Something went wrong'
               });
    } else if (err instanceof TypeError) {
        return res.status(400).json({ error: 'Type Error: Bad request' });
    }
 
    res.status(500).json({ error: 'Internal Server Error' });
};
 
app.get('/', (req, res) => {
    console.log('Home');
    res.send('Home Page');
})
 
// Route that simulates a different error (TypeError)
app.get('/type-error', (req, res, next) => {
    try {
        // Simulate a different error by causing a type error
        const undefinedVariable = undefined;
        // This will throw a TypeError
        console.log(undefinedVariable.property);
    } catch (error) {
        next(error);
    }
});
 
// Route that simulates a custom error
app.get('/custom-error', (req, res, next) => {
    try {
        // Simulate a custom error by throwing an exception
        throw new MyCustomError('This is a simulated custom error');
    } catch (error) {
        next(error);
    }
});
 
 
// Error handling middleware (should be placed at the end)
app.use(errorHandler);
 
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


Step to run the application: Run the below command in terminal

node index.js

Output:

Animation18



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads