Fix Prisma

1 fix: error koneksi Prisma dengan retry mechanism
      2
      3 Perubahan:
      4 - src/lib/prisma.ts: Tambah retry (3x) dengan exponential backoff saat connect
      5 - src/lib/prisma-retry.ts: NEW - Utility wrapper untuk retry operations
      6 - src/app/api/user-validate/route.ts: Improve error logging dengan detail
      7 - src/middleware.tsx: Clean up commented code
      8
      9 Fitur:
     10 - Auto retry saat database connection gagal
     11 - Explicit () di production
     12 - Better error logging untuk debugging
     13 - Reusable retry wrapper (withRetry, withTimeout)
     14
     15 Testing:
     16 - Build berhasil 
     17 - Type checking passed 
     18
     19 Fixes: Error in PostgreSQL connection: Error { kind: Closed, cause: None }

### No Issue
This commit is contained in:
2026-03-03 15:30:34 +08:00
parent df5d1aad48
commit f64ae42825
4 changed files with 245 additions and 7 deletions

View File

@@ -36,6 +36,40 @@ if (process.env.NODE_ENV === "production") {
},
},
});
// Explicitly connect to database dengan retry
const maxRetries = 3;
let retryCount = 0;
const connectWithRetry = async () => {
while (retryCount < maxRetries) {
try {
await prisma.$connect();
console.log('✅ PostgreSQL connected successfully');
return;
} catch (error) {
retryCount++;
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
console.error(`❌ PostgreSQL connection attempt ${retryCount}/${maxRetries} failed:`, errorMsg);
if (retryCount >= maxRetries) {
console.error('❌ All database connection attempts failed. Application will continue but database operations will fail.');
throw error;
}
// Wait before retry (exponential backoff)
const waitTime = Math.min(1000 * Math.pow(2, retryCount), 10000);
console.log(`⏳ Retrying in ${waitTime}ms...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
};
// Initialize connection (non-blocking)
connectWithRetry().catch(err => {
console.error('Failed to initialize database connection:', err);
});
} else {
if (!global.prisma) {
global.prisma = new PrismaClient({
@@ -65,6 +99,14 @@ if (!global.prismaListenersAdded) {
process.exit(0);
});
// Handle uncaught errors
process.on("uncaughtException", async (error) => {
if (error.message.includes("Prisma") || error.message.includes("database")) {
console.error("Uncaught database error:", error);
await prisma.$disconnect();
}
});
// Tandai bahwa listener sudah ditambahkan
global.prismaListenersAdded = true;
}