I'm trying to prevent prisma from from shutting my app down even if it fails to connect to the database, so that my health-check
endpoint can still be reached. The error I get is this:
throw new PrismaClientInitializationError(error2.message, this.config.clientVersion, error2.error_code);
^
Error: Can't reach database server at `postgres`:`5432`
Please make sure your database server is running at `postgres`:`5432`.
at startFn (/home/my_name/my_folder/my-service/node_modules/@prisma/client/runtime/index.js:27186:17)
at Proxy.onModuleInit (/home/my_name/my_folder/my-service/src/services/prisma.ts:12:5)
which makes sense, because my database is shut off. But this crashes my nest application.
The prisma docs say that the PrismaClientInitializationError is returned whenprisma.$connect
runs, or if a query is run.
The obvious solution to me was to wrap this.$connect
with a try catch to prevent it from crashing and burning. So here is my attempt in my PrismaService
- the file that the error above is complaining about my-service/src/services/prisma
:
import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient, Prisma } from '@prisma/client';
@Injectable()
export class PrismaService
extends PrismaClient<Prisma.PrismaClientOptions, 'query' | 'error'>
implements OnModuleInit
{
constructor() {
try {
super();
} catch (e) {
console.log(e);
}
}
async onModuleInit() {
this.$on('error', (event) => {
console.log(event.target);
});
try {
await this.$connect();
} catch (e) {
console.log(e);
}
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}
It's littered with console logs, and none of them log anything to the console. In fact, I found that even if I delete this.$connect
if my database is up and running then prisma still connects to the database. If my database is not running I still get the same error message as above.
My question is, where do I need to put a try catch in order to prevent prisma from breaking my app?
And to satisfy my curiosity, why is the prisma client seemingly initializing itself even if I don't run this.$connect
This issue has seemingly resolved itself. and my error handling now works. I'm suspecting that because I was using docker compose
with mounted volumes some sort of caching was getting in the way and not registering that I had put a try/catch there