[Fixed] TypeError: Cannot read properties of undefined (reading 'data') at errorHandler – Javascript

by
Ali Hasan
express node.js prisma react-typescript

The Problem:

Problem Statement:

You are encountering a TypeError with the message "Cannot read properties of undefined (reading ‘data’)" when making POST, PATCH, or PUT requests to your Express.js API. This error occurs specifically in the error handling middleware (errorHandler.js) and is likely related to an issue with accessing the req.body or res.data properties.

The issue appears to be specific to POST, PATCH, or PUT requests, as GET requests are working as expected. You have attempted troubleshooting steps by uninstalling and reinstalling relevant packages (Express.js, Prisma, and express-async-errors), but the issue persists.

Further investigation reveals that commenting out the Prisma logic in the createManyCategories function does not resolve the error, indicating that the issue may lie elsewhere in your code or middleware configuration.

The Solutions:

Solution 1: Check for undefined properties before accessing them

The error occurs because the err.response object is undefined when performing the following check:

if (err.response.data.errorCode === "500.001.1001") {
  ...
}

To resolve this issue, it is advised to enhance the error handler with checks to determine if the required properties are defined before attempting to access them. An improved version of the errorHandler function below:

function errorHandler(
  err: ErrorObj,
  req: Request,
  res: Response,
  next: NextFunction
) {
  let customError: CustomErr = {
    statusCode: err.statusCode || 500,
    msg: err.message || "Something went wrong, please try again later",
  };

  // Check if err.response is defined
  if (err.response) {
    // Check if err.response.data is defined
    if (err.response.data) {
      // Handle error based on err.response.data.errorCode
      if (err.response.data.errorCode === "500.001.1001") {
        customError.msg = err.response.data.errorMessage;
        customError.statusCode = 400;
      }
    }
  }

  // Handle other error conditions here...

  console.log(err);
  return res.status(customError.statusCode).json({ error: customError.msg });
}

With these checks in place, the error handler will only attempt to access properties of the err.response object if they are defined, preventing the "Cannot read properties of undefined" error from occurring.

Q&A

What does the error "TypeError: Cannot read properties of undefined (reading ‘data’) at errorHandler" usually mean?

The error typically indicates that you are trying to access a property of an object that is undefined.

Is there an if statement checking if a variable in the error handler from this error is undefined?

Yes, there is an if statement checking if err.response is undefined. However, it doesn’t include checks to determine whether err, response data are undefined.

Video Explanation:

The following video, titled "How To Fix 'Uncaught TypeError: Cannot read properties of undefined'", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Want To Become A Developer? Checkout The Courses Here And Get Started - https://courses.selftaught-dev.com/ Join Discord ...