How to write Custom Error Handler Middleware in Express.js using JavaScript 👩‍💻

Bentil Shadrack - Aug 20 '22 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .