fix: add try-catch to all OnModuleInit hooks to prevent startup crashes
Some checks failed
Deploy API Server / build-and-deploy (push) Failing after 34s

- PrismaService.onModuleInit: catch DB connection failures
- CostAggregationService.onModuleInit: catch aggregation errors
- MetricsCleanupService.onModuleInit: catch cleanup errors

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
WangDL 2026-05-24 12:48:30 +08:00
parent 4a924a24fa
commit f0ddd7cf38
3 changed files with 16 additions and 5 deletions

View File

@ -1,4 +1,4 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
@ -6,8 +6,15 @@ export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
private readonly logger = new Logger(PrismaService.name);
async onModuleInit() {
try {
await this.$connect();
this.logger.log('Database connected');
} catch (err: any) {
this.logger.error(`Database connection failed: ${err.message}`);
}
}
async onModuleDestroy() {

View File

@ -11,7 +11,11 @@ export class CostAggregationService implements OnModuleInit, OnModuleDestroy {
constructor(private readonly prisma: PrismaService) {}
async onModuleInit() {
try {
await this.aggregateToday();
} catch (err: any) {
this.logger.warn(`Initial cost aggregation failed: ${err.message}`);
}
this.timer = setInterval(() => this.aggregateToday(), AGGREGATE_INTERVAL_MS);
}

View File

@ -12,8 +12,8 @@ export class MetricsCleanupService implements OnModuleInit, OnModuleDestroy {
constructor(private readonly prisma: PrismaService) {}
async onModuleInit() {
await this.cleanup();
this.timer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
await this.cleanup().catch(() => {});
this.timer = setInterval(() => this.cleanup().catch(() => {}), CLEANUP_INTERVAL_MS);
}
onModuleDestroy() {