Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 20, 2022 09:00 pm GMT

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.jsconst 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

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 appconst app = express();// MIDDLEWARESapp.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)

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


Original Link: https://dev.to/qbentil/how-to-write-custom-error-handler-middleware-in-expressjs-using-javascript-29j1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To