Cannot read properties of undefined (reading ‘handleRequest’)

  Kiến thức lập trình

I am fairly new to backend and Object Oriented Programming in general, especially JavaScript, and was working on something when I came across this error which says

Cannot read properties of undefined (reading 'handleRequest')

I have a ‘base.controller.ts’ file that contains a function called ‘handleRequest’. The idea is to extend my other Controllers with this Base Controller so that I can minimize code duplication.

Here is my ‘base.controller.ts’ file

import { Response, NextFunction } from "express";

// Define a type for service results
interface IServiceResult {
  message: string;
  code: number;
  data?: any;
}

// BaseController class
export default class BaseController {
  handleRequest = async (
    serviceFunction: (params: any) => Promise<IServiceResult>,
    params: any,
    response: Response,
    next: NextFunction
  ): Promise<void> => {
    try {
      const { message, code, data } = await serviceFunction(params);
      response.status(code).json({
        status: "ok",
        message,
        data,
      });
    } catch (error) {
      console.error("Unhandled Error:", error); // Debug logging
      next(error);
    }
  };
}

Here’s an example from my ‘auth.controller.ts’ file.

import { NextFunction, Request, Response } from "express";

import BaseController from "./base.controller";

import {
  loginService,
  registerService,
  logoutService,
  statusService,
} from "@/services/auth";

class AuthController extends BaseController {
  async login(
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> {
    const { email, password } = request.body;
    try {
      await this.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

  async register(
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> {
    const { firstName, lastName, email, password } = request.body;

    try {
      await this.handleRequest(
        registerService,
        { firstName, lastName, email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }
}

export default new AuthController();

I am pretty confident in building stuff out using the “everything in one file” way but I wanna learn how to do things in a neat and maintainable/manageable fashion.

I tried extending my Auth Controller with my Base Controller, expecting it to have access to methods from the parent class, i.e. Base Controller, but for some reason it is not able to do that.

I suspect somethings wrong with how ‘this’ is bind in JavaScript but not sure how to fix this error.

Also, would love to learn if there is a better way to do this.

New contributor

Nadeem Ashraf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

So this is referring to your extended/child class AuthController.

As you are trying to refer to a method in the parent BaseController class, you would actually want to use a call to super.

Since you are trying to call a method that doesn’t exist in this class, you are getting undefined.

i.e.

try {
      await this.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

actually becomes:

    try {
      await super.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

Here is a related SO post

1

This is just a wild guess but it looks like how you declared handleRequest in you abstract class will make it not public so not defined in any inheriting class.

async handleRequest() {
 ...
}

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

Cannot read properties of undefined (reading ‘handleRequest’)

I am fairly new to backend and Object Oriented Programming in general, especially JavaScript, and was working on something when I came across this error which says

Cannot read properties of undefined (reading 'handleRequest')

I have a ‘base.controller.ts’ file that contains a function called ‘handleRequest’. The idea is to extend my other Controllers with this Base Controller so that I can minimize code duplication.

Here is my ‘base.controller.ts’ file

import { Response, NextFunction } from "express";

// Define a type for service results
interface IServiceResult {
  message: string;
  code: number;
  data?: any;
}

// BaseController class
export default class BaseController {
  handleRequest = async (
    serviceFunction: (params: any) => Promise<IServiceResult>,
    params: any,
    response: Response,
    next: NextFunction
  ): Promise<void> => {
    try {
      const { message, code, data } = await serviceFunction(params);
      response.status(code).json({
        status: "ok",
        message,
        data,
      });
    } catch (error) {
      console.error("Unhandled Error:", error); // Debug logging
      next(error);
    }
  };
}

Here’s an example from my ‘auth.controller.ts’ file.

import { NextFunction, Request, Response } from "express";

import BaseController from "./base.controller";

import {
  loginService,
  registerService,
  logoutService,
  statusService,
} from "@/services/auth";

class AuthController extends BaseController {
  async login(
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> {
    const { email, password } = request.body;
    try {
      await this.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

  async register(
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> {
    const { firstName, lastName, email, password } = request.body;

    try {
      await this.handleRequest(
        registerService,
        { firstName, lastName, email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }
}

export default new AuthController();

I am pretty confident in building stuff out using the “everything in one file” way but I wanna learn how to do things in a neat and maintainable/manageable fashion.

I tried extending my Auth Controller with my Base Controller, expecting it to have access to methods from the parent class, i.e. Base Controller, but for some reason it is not able to do that.

I suspect somethings wrong with how ‘this’ is bind in JavaScript but not sure how to fix this error.

Also, would love to learn if there is a better way to do this.

New contributor

Nadeem Ashraf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

So this is referring to your extended/child class AuthController.

As you are trying to refer to a method in the parent BaseController class, you would actually want to use a call to super.

Since you are trying to call a method that doesn’t exist in this class, you are getting undefined.

i.e.

try {
      await this.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

actually becomes:

    try {
      await super.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

Here is a related SO post

1

This is just a wild guess but it looks like how you declared handleRequest in you abstract class will make it not public so not defined in any inheriting class.

async handleRequest() {
 ...
}

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT