From fe7683f5b1e1317a8cc4a1a00d040710c664b2b4 Mon Sep 17 00:00:00 2001 From: Mathis HERRIOT <197931332+0x485254@users.noreply.github.com> Date: Mon, 9 Feb 2026 09:52:40 +0100 Subject: [PATCH] feat(cache): enhance error handling and logging for cache operations - Added try-catch blocks to improve resilience in cache operations across services. - Integrated detailed error logging for better debugging. - Updated Redis reconnect strategy with exponential backoff and logging. --- backend/src/app.module.ts | 31 ++++++++++++++----- backend/src/categories/categories.service.ts | 8 +++-- .../crawler-detection.middleware.ts | 25 ++++++++++----- backend/src/contents/contents.service.ts | 8 +++-- backend/src/users/users.service.ts | 8 +++-- 5 files changed, 59 insertions(+), 21 deletions(-) diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index decd20d..44e0942 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -1,5 +1,10 @@ import { CacheModule } from "@nestjs/cache-manager"; -import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common"; +import { + Logger, + MiddlewareConsumer, + Module, + NestModule, +} from "@nestjs/common"; import { ConfigModule, ConfigService } from "@nestjs/config"; import { ScheduleModule } from "@nestjs/schedule"; import { ThrottlerModule } from "@nestjs/throttler"; @@ -70,12 +75,24 @@ import { UsersModule } from "./users/users.module"; isGlobal: true, imports: [ConfigModule], inject: [ConfigService], - useFactory: async (config: ConfigService) => ({ - store: await redisStore({ - url: `redis://${config.get("REDIS_HOST")}:${config.get("REDIS_PORT")}`, - }), - ttl: 600, // 10 minutes - }), + useFactory: async (config: ConfigService) => { + const logger = new Logger("RedisCache"); + return { + store: await redisStore({ + url: `redis://${config.get("REDIS_HOST")}:${config.get("REDIS_PORT")}`, + socket: { + reconnectStrategy: (retries) => { + const delay = Math.min(retries * 50, 2000); + logger.warn( + `Redis connection lost. Retrying in ${delay}ms (attempt ${retries})`, + ); + return delay; + }, + }, + }), + ttl: 600, // 10 minutes + }; + }, }), ], controllers: [AppController, HealthController], diff --git a/backend/src/categories/categories.service.ts b/backend/src/categories/categories.service.ts index ddfbba0..ff38b43 100644 --- a/backend/src/categories/categories.service.ts +++ b/backend/src/categories/categories.service.ts @@ -15,8 +15,12 @@ export class CategoriesService { ) {} private async clearCategoriesCache() { - this.logger.log("Clearing categories cache"); - await this.cacheManager.del("categories/all"); + try { + this.logger.log("Clearing categories cache"); + await this.cacheManager.del("categories/all"); + } catch (error) { + this.logger.error(`Error clearing categories cache: ${error.message}`); + } } async findAll() { diff --git a/backend/src/common/middlewares/crawler-detection.middleware.ts b/backend/src/common/middlewares/crawler-detection.middleware.ts index 2d42ec3..ad706f0 100644 --- a/backend/src/common/middlewares/crawler-detection.middleware.ts +++ b/backend/src/common/middlewares/crawler-detection.middleware.ts @@ -49,13 +49,18 @@ export class CrawlerDetectionMiddleware implements NestMiddleware { const userAgent = req.get("user-agent") || "unknown"; // Vérifier si l'IP est bannie - const isBanned = await this.cacheManager.get(`banned_ip:${ip}`); - if (isBanned) { - this.logger.warn(`Banned IP attempt: ${ip} -> ${method} ${url}`); - res.status(403).json({ - message: "Access denied: Your IP has been temporarily banned.", - }); - return; + try { + const isBanned = await this.cacheManager.get(`banned_ip:${ip}`); + if (isBanned) { + this.logger.warn(`Banned IP attempt: ${ip} -> ${method} ${url}`); + res.status(403).json({ + message: "Access denied: Your IP has been temporarily banned.", + }); + return; + } + } catch (error) { + this.logger.error(`Error checking ban status for IP ${ip}: ${error.message}`); + // On continue même en cas d'erreur Redis pour ne pas bloquer les utilisateurs légitimes } res.on("finish", async () => { @@ -73,7 +78,11 @@ export class CrawlerDetectionMiddleware implements NestMiddleware { ); // Bannir l'IP pour 24h via Redis - await this.cacheManager.set(`banned_ip:${ip}`, true, 86400000); + try { + await this.cacheManager.set(`banned_ip:${ip}`, true, 86400000); + } catch (error) { + this.logger.error(`Error banning IP ${ip}: ${error.message}`); + } } } }); diff --git a/backend/src/contents/contents.service.ts b/backend/src/contents/contents.service.ts index 80e63ce..5a2d0d6 100644 --- a/backend/src/contents/contents.service.ts +++ b/backend/src/contents/contents.service.ts @@ -34,8 +34,12 @@ export class ContentsService { ) {} private async clearContentsCache() { - this.logger.log("Clearing contents cache"); - await this.cacheManager.clear(); + try { + this.logger.log("Clearing contents cache"); + await this.cacheManager.del("contents/all"); + } catch (error) { + this.logger.error(`Error clearing contents cache: ${error.message}`); + } } async getUploadUrl(userId: string, fileName: string) { diff --git a/backend/src/users/users.service.ts b/backend/src/users/users.service.ts index 0876925..1c28708 100644 --- a/backend/src/users/users.service.ts +++ b/backend/src/users/users.service.ts @@ -33,8 +33,12 @@ export class UsersService { ) {} private async clearUserCache(username?: string) { - if (username) { - await this.cacheManager.del(`users/profile/${username}`); + try { + if (username) { + await this.cacheManager.del(`users/profile/${username}`); + } + } catch (error) { + this.logger.error(`Error clearing user cache: ${error.message}`); } }