DEV Community

Cover image for AppError=> Develop an AppError class in TypeScript for a MERN application utilizing Mongoose for MongoDB integration.
Kazi Abdur Rakib
Kazi Abdur Rakib

Posted on

AppError=> Develop an AppError class in TypeScript for a MERN application utilizing Mongoose for MongoDB integration.

//src/app/errors/AppError.ts

class AppError extends Error {
  public statusCode: number;

  constructor(statusCode: number, message: string, stack = '') {
    super(message);
    this.statusCode = statusCode;

    if (stack) {
      this.stack = stack;
    } else {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

export default AppError;

Enter fullscreen mode Exit fullscreen mode

where i am using this AppError function

//src/app/modules/academicDepartment/academicDepartment.model.ts

academicDepartmentSchema.pre('save', async function (next) {
  const isDepartmentExist = await AcademicDepartment.findOne({
    name: this.name,
  });

  if (isDepartmentExist) {
    throw new AppError(
      httpStatus.NOT_FOUND,
      'This department is already exist!',
    );
  }

  next();
});

academicDepartmentSchema.pre('findOneAndUpdate', async function (next) {
  const query = this.getQuery();
  const isDepartmentExist = await AcademicDepartment.findOne(query);

  if (!isDepartmentExist) {
    throw new AppError(
      httpStatus.NOT_FOUND,
      'This department does not exist! ',
    );
  }

  next();
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)