Cannot read properties of undefined (reading ‘handleRequest’) | JavaScript

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

Help is appreciated.
Thanks in advance.

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật