DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Bentil Shadrack
Bentil Shadrack

Posted on • Updated on

How to write Custom Error Handler Middleware in Express.js using JavaScript πŸ‘©β€πŸ’»

What is Error Handler

Error handler is responsible of identifying and handling runtime issues.
Express.js comes pre-configured with a built-in Error Handler by default.

Error Handlers In ExpressJSπŸš€

Whenever a server error occurs, Express.js detects it and, unless you have a custom error handler, uses its built-in error handler to send a response to the client with the error message. Not only is Express.JS keen to handler errors properly but also to correctly empty away any unused resources when the application starts up again.

How to write Custom Error Handler Middleware in Express.js using JavaScriptπŸš€

1. Create Custom ErrorHandler middleware

Folder Structure

// ErrorHandler.js
const ErrorHandler = (err, req, res, next) => {
    console.log("Middleware Error Hadnling");
    const errStatus = err.statusCode || 500;
    const errMsg = err.message || 'Something went wrong';
    res.status(errStatus).json({
        success: false,
        status: errStatus,
        message: errMsg,
        stack: process.env.NODE_ENV === 'development' ? err.stack : {}
    })
}

export default ErrorHandler
Enter fullscreen mode Exit fullscreen mode

NOTE: _ err.stack shows the exact file and line number the error occured. This is only needed in developement mode to debug your code. It becomes dangerous when your project structure is exposed on production_

2. Attach Custom Error Handler as The Last Middleware to Use

// index.js (Server Entery File)
import { AuthRoute, CategoryRoute, HomeRoute, PostRoute, UserRoute } from "./routes/index.routes.js";

import ErrorHandler from "./middlewares/ErrorHandler.js";


// init app
const app = express();


// MIDDLEWARES
app.use("/", HomeRoute);
app.use("/user", verifyAccessToken, UserRoute);
app.use("/categories", CategoryRoute);
app.use("/posts", PostRoute)
app.use("/auth", AuthRoute);

// ERROR HANDLER MIDDLEWARE (Last middleware to use)
app.use(ErrorHandler)

Enter fullscreen mode Exit fullscreen mode

3. How to Call the ErrorHandler

to call the ErrorHandler, Use the next() in Express.
The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

app.use("/books", (req, res, next) => {
  try{
      // code block to be executed
  }catch(err){
    next(err);
  }
})
Enter fullscreen mode Exit fullscreen mode

Sample Error Response on Production

production error

Sample Error Response in developementβœ”

Developemnt error

Why Should I Create Custom ErrorHandler instead of using the built-in ErrorHandlerπŸ‘€

You might want to create a custom errorhandler for a number of reasons.
For instance, some projects don't set NODE_ENV to "production" during the production stages. If error is not handled correctly, this could result in the disclosure of sensitive information about the server.
Other projects needs different error object format be sent at different points.

As a developer, It is very important to handler all error correctly to avoid crushing your APP anytime an error occurs.

Bentil hereπŸš€
If you like my content, you can support me here to keep up the work.πŸ‘‡

buy me a coffee

Let me know your questions or suggestions in the comment box below

Top comments (6)

Collapse
 
ethel3 profile image
Ethel Akrasi Akosua

This piece was very helpful.

Collapse
 
qbentil profile image
Bentil Shadrack Author

Thank youu

Collapse
 
yogeshyadav profile image
Yogesh Yadav

This was simple and straightforward. Thanks for sharing.

Collapse
 
qbentil profile image
Bentil Shadrack Author

I am glad you like itβœ¨πŸš€

Collapse
 
nanaole profile image
Offei Emmanuel

I will try it. N thanks to the creator of d content. You putting out priceless information for free..... πŸ’―. Continue the good work.

Collapse
 
qbentil profile image
Bentil Shadrack Author

You are most welcome
I'm glad you like it

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post