DEV Community

krishna-Tiwari
krishna-Tiwari

Posted on

How to handle custom error handling in express js

what is error handler

an error handler is a function that is called when an error occurs in an application. In the context of web development with Node.js and Express, an error handler is a middleware function that is used to handle errors that occur during the request-response cycle.

purpose of error handler

The purpose of an error handler is to ensure that errors are properly handled and that the user is presented with an appropriate error message or response. An error handler can also be used to log error details, debug the application, and prevent the application from crashing.

error handling in express

In Express, error handlers are defined as middleware functions that have an extra parameter for the err object. If an error occurs in any middleware function or route handler, Express will automatically call the error handler with the err object as the first parameter. The error handler can then inspect the err object and take appropriate action based on the error type and context.

Haha,๐Ÿ˜‚๐Ÿ˜‚ I think you got some confusion. Ok ๐Ÿ‘Œ Don't worry i am here to help you right ๐Ÿ‘‰ .
Ok let's dive into the example and procedure

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

Boom ๐Ÿ’ฅ

  1. ### Create Custom ErrorHandler middleware

Image description

Don't worry here's a code

// 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 which file and where the error comes from. This is only needed in developement mode to debug your code. It becomes dangerous when your project structure is exposed on production. Always use NODE_ENV to development during development.

  1. ### Attach Custom Error Handler as The Last Middleware to Use

Note that the error handling middleware function should always be the last middleware function registered in the app, so that it can catch any errors thrown by other middleware functions or route handlers.

const express = require('express);

//initializing server instanse
const app = express();

const ErrorHandler = require(./middlewares/ErrorHandler.j)
//routes and other middlewares

//eroor hanlder middleware at last middleware
app.use(ErrorHandler);
Enter fullscreen mode Exit fullscreen mode

3. How to Call the ErrorHandler then ๐Ÿ˜•

To call an error handler in a custom Express application, you can define a middleware function that passes an error object to the next middleware function using the next() function.
Here's an example:

// Define an error handling middleware function
function errorHandler(err, req, res, next) {
  res.status(err.statusCode || 500);
  res.json({
    error: {
      message: err.message,
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

use middlewares as

// Register middleware functions in the Express app
const express = require("express");
const app = express();
app.use(myMiddleware);
app.use(errorHandler);
Enter fullscreen mode Exit fullscreen mode

In this example, the myMiddleware function throws a custom error by creating a new instance of the MyCustomError class and passing it to the next middleware function using the next() function.

The errorHandler function is then called because the error was passed to the next middleware function with the next() function. The errorHandler function inspects the error object, sets the HTTP status code and returns a JSON response with an error message.

why should i use custom error handler in web application

Improved error messages: By defining your own error classes and error messages, you can provide more specific and informative error messages to your users, which can help them understand and resolve errors more easily.

Consistent error handling: By using a custom error handler, you can ensure that errors are handled consistently across all parts of your application. This can help to avoid confusion and improve the overall user experience.

Error logging: By defining a custom error handler, you can log error details to a file or a logging service, which can help you to identify and fix errors more quickly.

Prevent application crashes: By properly handling errors in your application, you can prevent your application from crashing or behaving unpredictably. This can help to ensure that your application remains stable and reliable, even in the face of unexpected errors.

Top comments (0)