@nestjs/common#InternalServerErrorException TypeScript Examples

The following examples show how to use @nestjs/common#InternalServerErrorException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: site.utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
handleDuplicateSite = (err) => {
  // Unique Violation: A site already exists at these coordinates
  if (err.code === '23505') {
    throw new BadRequestException('A site already exists at these coordinates');
  }

  logger.error('An unexpected error occurred', err);
  throw new InternalServerErrorException('An unexpected error occurred');
}
Example #2
Source File: doubt.service.ts    From edu-server with MIT License 6 votes vote down vote up
// add a new doubtAnswer
  async addNewDoubtAnswer(
    doubtId: Schema.Types.ObjectId,
    createDoubtAnswerDto: CreateDoubtAnswerDto,
  ) {
    try {
      const doubt = await this.DoubtModel.findById(doubtId);
      const user = await this.UserModel.findOne({
        email: this.request['user']['email'],
      });
      if (doubt) {
        const doubtAnswerToBeCreated = {
          ...createDoubtAnswerDto,
          photoUrl: user.photoUrl,
        };
        const newDoubtAnswer = await new this.DoubtAnswerModel(
          doubtAnswerToBeCreated,
        ).save();
        doubt.answers.push(newDoubtAnswer);
        await doubt.save();
        return newDoubtAnswer;
      } else {
        throw new NotFoundException(
          'The doubt id is invalid or the doubt no longer exists',
        );
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #3
Source File: config.service.ts    From nest-react with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
   * Extract the configuration from a `dotenv` file
   * @param env The environment name. Corresponding `name.env` file will be used. Default to `local`
   */
  private getConfigFromEnvFile(env = 'local'): DotenvParseOutput {
    const envFilePath = join('env', `.env.${env}`);
    try {
      const config = parse(readFileSync(envFilePath));
      return config;
    } catch (err) {
      const msg = `Configuration error, see below:

/!\\ No environment definition found at ${envFilePath}. Please choose one of the following options (in preference order):
  1. Set both the CONFIG_PATH and the SECRETS_PATH environment variables and fill their respective folders with corresponding environment values.
  2. Set the NODE_ENV environment variable and attach the corresponding "dotenv" file to the server.

`;
      this.logger.error(msg);
      throw new InternalServerErrorException();
    }
  }
Example #4
Source File: user.service.ts    From edu-server with MIT License 6 votes vote down vote up
// adds wishlisted course
  async addWishlist(cId: Schema.Types.ObjectId) {
    try {
      const user = await this.userModel.findOne({
        email: this.request['user']['email'],
      });

      if (user) {
        const doesWishlistExists = await this.courseModel.exists({
          _id: cId['cId'],
        });
        if (doesWishlistExists) {
          const doesUserExistInWishList = user.wishlist.includes(cId['cId']);
          if (!doesUserExistInWishList) {
            user.wishlist.push(cId['cId']);
            await user.save();
            return user;
          } else {
            throw new ConflictException('Course Already Exists In WishList');
          }
        } else {
          throw new NotFoundException("Wishlisted Course doesn't exist");
        }
      } else {
        throw new NotFoundException('User Not Found');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #5
Source File: user.repository.ts    From pknote-backend with GNU General Public License v3.0 6 votes vote down vote up
async register(authCredentialsDto: AuthCredentialsDto): Promise<void> {
    const { phone, pwd } = authCredentialsDto;

    // const exists = this.findOne({ username })

    // if (exists) {
    //   // throw some error
    // }
    // const salt = await bcrypt.genSalt()
    // console.log('TCL: UserRepository -> salt', salt)

    // const user = new User()
    const user = this.create();
    user.phone = phone;
    user.salt = await bcrypt.genSalt();
    user.pwd = await this.hashPassword(pwd, user.salt);
    user.userId = uuid();

    try {
      await user.save();
    } catch (error) {
      if (error.code === '23505') {
        // duplicate username
        throw new ConflictException('Username already exists');
      } else {
        throw new InternalServerErrorException();
      }
    }
  }
Example #6
Source File: release-notes.controller.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
@Get()
  async getReleaseNotes(): Promise<GetReleaseNotesResponse> {
    const response: GetReleaseNotesResponse = {
      lastUpdatedUnixTime: null,
      releaseNotes: null,
    };
    const request = await this.httpService
      .get(
        'https://notion-api.splitbee.io/v1/page/abba246bfa0847baa2706ab30d0c6c7d',
      )
      .toPromise();
    const data = request.data;
    try {
      const timeText =
        data[process.env.RELEASE_NOTE_TIMESTAMP_ID]?.value?.properties
          ?.title[0][0];
      response.lastUpdatedUnixTime = timeText.split('Unix ')[1] * 1000;
    } catch (e) {
      throw new InternalServerErrorException(
        ERROR_MESSAGES.releaseNotesController.releaseNotesTime(e),
      );
    }
    // Remove the time block and page link block from page
    data[process.env.RELEASE_NOTE_TIMESTAMP_ID].value.properties.title = [];
    data[process.env.WANT_TO_SEE_MORE_ID].value.properties.title = [];
    response.releaseNotes = data;
    return response;
  }
Example #7
Source File: user.service.ts    From edu-server with MIT License 6 votes vote down vote up
// Delete Enrolled Course of User
  async deleteEnrolledCourse(courseId: Schema.Types.ObjectId): Promise<any> {
    let deletedFrom;
    try {
      const user = await this.userModel.findOne({
        email: this.request['user']['email'],
      });
      if (user) {
        const userId = user.id;
        deletedFrom = await this.enrolledModel.findOneAndRemove({
          studentId: userId,
          courseId: courseId,
        });
        if (deletedFrom) {
          return deletedFrom;
        } else {
          throw new NotFoundException('not found');
        }
      } else {
        throw new NotFoundException('User not found');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #8
Source File: upload-hobo-data.ts    From aqualink-app with MIT License 6 votes vote down vote up
handleEntityDuplicate = <T>(
  repository: Repository<T>,
  query: (
    repository: Repository<T>,
    polygon?: GeoJSON | null,
  ) => Promise<T | undefined>,
  polygon?: GeoJSON | null,
) => {
  return (err) => {
    // Catch unique violation, i.e. there is already a site at this location
    if (err.code === '23505') {
      return query(repository, polygon).then((found) => {
        if (!found) {
          throw new InternalServerErrorException(
            'Could not fetch conflicting entry',
          );
        }

        return found;
      });
    }

    throw err;
  };
}
Example #9
Source File: course.service.ts    From edu-server with MIT License 6 votes vote down vote up
// edit course by Id
  async editCourse(
    courseId: Schema.Types.ObjectId,
    updateCourseDTO: UpdateCourseDTO,
  ): Promise<Course> {
    let updatedCourse = null;
    try {
      updatedCourse = await this.CourseModel.findByIdAndUpdate(
        courseId,
        updateCourseDTO,
        { new: true },
      ).exec();
    } catch (e) {
      throw new InternalServerErrorException(e);
    } finally {
      return updatedCourse;
    }
  }
Example #10
Source File: client-not-found.exception.ts    From nestjs-oauth2-server-module with MIT License 5 votes vote down vote up
/**
     * Kind message with client ID
     *
     * @param name
     */
    static withName(name: string): InternalServerErrorException {
        return new UnauthorizedException(`The client with name "${name}" was not found`);
    }
Example #11
Source File: upload-hobo-data.ts    From aqualink-app with MIT License 5 votes vote down vote up
createSites = async (
  sites: Partial<Site>[],
  user: User,
  siteRepository: Repository<Site>,
  userRepository: Repository<User>,
  historicalMonthlyMeanRepository: Repository<HistoricalMonthlyMean>,
) => {
  logger.log('Saving sites');
  const siteEntities = await Promise.all(
    sites.map((site) =>
      siteRepository
        .save(site)
        .catch(handleEntityDuplicate(siteRepository, siteQuery, site.polygon)),
    ),
  );

  logger.log(`Saving monthly max data`);
  await Bluebird.map(
    siteEntities,
    (site) => {
      const point: Point = site.polygon as Point;
      const [longitude, latitude] = point.coordinates;

      return Promise.all([
        getHistoricalMonthlyMeans(longitude, latitude),
        historicalMonthlyMeanRepository.findOne({ where: { site } }),
      ]).then(([historicalMonthlyMean, found]) => {
        if (found || !historicalMonthlyMean) {
          logger.warn(`Site ${site.id} has already monthly max data`);
          return null;
        }

        return historicalMonthlyMean.map(({ month, temperature }) => {
          return (
            temperature &&
            historicalMonthlyMeanRepository.save({ site, month, temperature })
          );
        });
      });
    },
    { concurrency: 4 },
  );

  // Create reverse map (db.site.id => csv.site_id)
  const dbIdToCSVId: Record<number, number> = Object.fromEntries(
    siteEntities.map((site) => {
      if (!site.name) {
        throw new InternalServerErrorException('Site name was not defined');
      }

      const siteId = parseInt(site.name.replace(SITE_PREFIX, ''), 10);
      return [site.id, siteId];
    }),
  );

  // Update administered sites relationship
  await userRepository.save({
    id: user.id,
    administeredSites: user.administeredSites.concat(siteEntities),
  });

  return { siteEntities, dbIdToCSVId };
}
Example #12
Source File: base.service.ts    From codeclannigeria-backend with MIT License 5 votes vote down vote up
protected static throwMongoError(err: MongoError): void {
    console.error(err);
    throw new InternalServerErrorException(err, err.errmsg);
  }
Example #13
Source File: user.service.ts    From edu-server with MIT License 5 votes vote down vote up
// adds Enrolled Course
  async addCourse(createEnrolledDTO: CreateEnrolledDTO) {
    try {
      const user = await this.userModel.findOne({
        email: this.request['user']['email'],
      });
      if (user) {
        const courseIdSearch = await this.enrolledModel
          .find({ studentId: user.id })
          .lean();
        courseIdSearch.forEach((singleEnrolled) => {
          if (singleEnrolled.courseId == createEnrolledDTO['courseId']) {
            throw new ConflictException('Course Already Enrolled by user');
          }
        });
        const newEnrolled = await new this.enrolledModel(createEnrolledDTO);

        const course = await this.courseModel.findById(
          createEnrolledDTO.courseId,
        );

        if (course) {
          newEnrolled['videosWatched'] = new Array(course.video_num).fill(
            false,
          );
          await newEnrolled.save();
          return newEnrolled;
        } else {
          throw new NotFoundException('course not found!');
        }

        // a test line to see the populated sets of data
        /*const newF = await this.enrolledModel.find({}).populate('students');
      return newF;*/
      } else {
        throw new NotFoundException('user not found!');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #14
Source File: http-env.e2e-spec.ts    From nest-xray with MIT License 4 votes vote down vote up
describe("HttpEnvironment (e2e)", () => {
  let app: INestApplication;

  let controller: HttpEnvController;
  let service: HttpEnvService;
  let xrayClient: XRayClient;
  let sendSegment: jest.SpyInstance<Segment>;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        TracingModule.forRoot({
          serviceName: "http-env-e2e-test",
          // EC2 plugin crashes in Github Actions
          plugins: [],
        }),
      ],
      providers: [HttpEnvService],
      controllers: [HttpEnvController],
    }).compile();

    app = moduleFixture.createNestApplication();
    app.enableShutdownHooks();
    await app.init();

    controller = app.get<HttpEnvController>(HttpEnvController);
    service = app.get<HttpEnvService>(HttpEnvService);
    xrayClient = app.get<XRayClient>(XRAY_CLIENT);

    sendSegment = segmentEmitterMock();
  });

  afterEach(async () => {
    await app.close();
    sendSegment.mockRestore();
  });

  it("should be defined", () => {
    expect(controller).toBeDefined();
    expect(service).toBeDefined();
    expect(xrayClient).toBeDefined();
  });

  it("should send a segment for a successful request", async () => {
    await request(app.getHttpServer())
      .get("/url")
      .expect(200)
      .expect("HttpEnv");

    expect(sendSegment).toHaveBeenCalledTimes(1);
    expect(sendSegment).toHaveBeenLastCalledWith(
      expect.objectContaining({
        name: "http-env-e2e-test",
        service: expect.objectContaining({ name: "@narando/nest-xray" }),
        http: expect.objectContaining({
          request: expect.objectContaining({
            client_ip: "::ffff:127.0.0.1",
            method: "GET",
            url: expect.stringMatching(/^http:\/\/127.0.0.1:[0-9]{1,5}\/url/),
            user_agent: expect.stringMatching(/^node-superagent/),
          }),
          response: expect.objectContaining({
            status: 200,
          }),
        }),
        subsegments: expect.arrayContaining([
          expect.objectContaining({ name: "http-env-e2e-test-subsegment" }),
        ]),
      })
    );
  });

  it("should correctly parse the request url when using query parameters", async () => {
    // Regression test for #140
    await request(app.getHttpServer()).get("/url?id=1234").expect(200);

    expect(sendSegment).toHaveBeenCalledTimes(1);

    const submittedURL = sendSegment.mock.calls[0][0].http.request.url;

    expect(submittedURL).toMatch(/^http:\/\/127.0.0.1:[0-9]{1,5}\/url$/);
  });

  it("should send a segment for a 4xx error", async () => {
    service.index = jest.fn().mockRejectedValue(new BadRequestException());

    await request(app.getHttpServer()).get("/url").expect(400);

    expect(sendSegment).toHaveBeenCalledTimes(1);
    expect(sendSegment).toHaveBeenLastCalledWith(
      expect.objectContaining({
        http: expect.objectContaining({
          request: expect.objectContaining({
            method: "GET",
            url: expect.stringMatching(/^http:\/\/127.0.0.1:[0-9]{1,5}\/url/),
          }),
          response: expect.objectContaining({
            status: 400,
          }),
        }),
      })
    );
  });

  it("should send a segment for a 5xx error", async () => {
    service.index = jest
      .fn()
      .mockRejectedValue(new InternalServerErrorException());

    await request(app.getHttpServer()).get("/url").expect(500);

    expect(sendSegment).toHaveBeenCalledTimes(1);
    expect(sendSegment).toHaveBeenLastCalledWith(
      expect.objectContaining({
        http: expect.objectContaining({
          request: expect.objectContaining({
            method: "GET",
            url: expect.stringMatching(/^http:\/\/127.0.0.1:[0-9]{1,5}\/url/),
          }),
          response: expect.objectContaining({
            status: 500,
          }),
        }),
      })
    );
  });
});
Example #15
Source File: user.entity.ts    From codeclannigeria-backend with MIT License 4 votes vote down vote up
@pre<User>('save', async function () {
  try {
    (this as Writable<User>).password = await hash(this.password, 10);
  } catch (e) {
    throw new InternalServerErrorException(e);
  }
})
@index({ email: 1 }, { unique: true })
// @plugin(autopopulate as any)
export class User extends BaseEntity {
  @prop({
    required: true,
    maxlength: columnSize.length64,
    trim: true,
    text: true
  })
  readonly firstName!: string;
  @prop({
    required: true,
    maxlength: columnSize.length64,
    trim: true,
    text: true
  })
  readonly lastName!: string;
  @prop({
    required: true,
    maxlength: columnSize.length64,
    trim: true,
    lowercase: true,
    text: true,
    unique: false
  })
  readonly email!: string;
  @prop({
    maxlength: columnSize.length64,
    trim: true,
    text: true,
    default: null
  })
  readonly phoneNumber!: string;
  @prop({ default: null })
  readonly photoUrl: string = null;
  @prop({
    maxlength: columnSize.length128,
    trim: true,
    text: true,
    default: null
  })
  readonly description!: string;
  @prop({
    maxlength: columnSize.length64,
    trim: true,
    text: true,
    default: null
  })
  readonly city: string = null;
  @prop({
    maxlength: columnSize.length64,
    trim: true,
    text: true,
    default: null
  })
  readonly country: string = null;
  @prop({
    enum: Gender,
    type: String,
    default: Gender.UNSPECIFIED
  })
  readonly gender: Gender = Gender.UNSPECIFIED;
  @prop({ type: Date, default: null })
  readonly dob: Date = null;
  @prop({ type: String, default: null })
  readonly technologies: string[] = [];
  @prop({ required: true, maxlength: columnSize.length64 })
  @Exclude()
  readonly password!: string;
  @Exclude()
  @prop({ default: 0 })
  readonly loginAttemptCount!: number;
  @prop({
    enum: UserRole,
    type: String,
    required: true,
    default: UserRole.MENTEE
  })
  readonly role = UserRole.MENTEE;
  @prop({ required: true, default: false })
  readonly isEmailVerified: boolean;
  @prop({ default: undefined })
  readonly lockOutEndDate?: Date;
  @prop({ required: true, default: 0 })
  readonly failedSignInAttempts!: number;
  @prop({ ref: Track, default: [] })
  readonly tracks: Ref<Track>[] = [];
  @prop({ default: 0 })
  readonly notifyCount: number;
  @prop({ default: 0 })
  readonly notifUnreadCount: number;
  /**
   * Get User's full name
   *
   * @readonly
   * @memberof User
   */
  get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  setRandomPass(): void {
    (this as Writable<User>).password = crypto
      .randomBytes(columnSize.length32)
      .toString();
  }
  confirmEmail(): void {
    (this as Writable<User>).isEmailVerified = true;
  }
  static get model(): ReturnModelType<typeof User> {
    return getModelForClass(this);
  }
}