,

Learning Express JS | 24. How to Create Custom Error Handler Middleware in Express JS Step by Step

Posted by

Belajar Express JS | 24. Cara Membuat Erorr Handler Custom Middleware Express JS Step by Step

Belajar Express JS | 24. Cara Membuat Erorr Handler Custom Middleware Express JS Step by Step

Middleware is a key concept in Express JS, allowing you to customize the behavior of your application. In this tutorial, we will learn how to create a custom error handler middleware in Express JS step by step.

Step 1: Create a new file for your custom error handler middleware

            
                const customErrorHandler = (err, req, res, next) => {
                    console.log(err);
                    res.status(500).json({ error: 'Something went wrong' });
                };

                module.exports = customErrorHandler;
            
        

Step 2: Include your custom error handler middleware in your Express app

            
                const express = require('express');
                const customErrorHandler = require('./customErrorHandler');

                const app = express();

                app.use(customErrorHandler);
            
        

Step 3: Test your custom error handler middleware

Now that you have created and included your custom error handler middleware in your Express app, you can test it by intentionally throwing an error in one of your routes.

            
                app.get('/test', (req, res, next) => {
                    next(new Error('This is a test error'));
                });
            
        

When you navigate to the ‘/test’ endpoint in your browser, you should see the custom error handler middleware kick in and return a JSON response with the message ‘Something went wrong’ and a status code of 500.

Congratulations, you have successfully created and implemented a custom error handler middleware in Express JS!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Lukmandst
4 months ago

mantap bang