From ebad24e304e31ef19e16aaa6d6e87cafcde0457e Mon Sep 17 00:00:00 2001 From: Vasyl Ivanchuk Date: Tue, 23 Apr 2024 12:33:35 +0300 Subject: [PATCH] fix: add log for failed api health / ready check --- .../api/src/health/health.controller.spec.ts | 28 +++++++++++++++++++ packages/api/src/health/health.controller.ts | 7 ++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/api/src/health/health.controller.spec.ts b/packages/api/src/health/health.controller.spec.ts index 0dde57d1df..9bfd136f56 100644 --- a/packages/api/src/health/health.controller.spec.ts +++ b/packages/api/src/health/health.controller.spec.ts @@ -1,3 +1,4 @@ +import { ServiceUnavailableException } from "@nestjs/common"; import { Test, TestingModule } from "@nestjs/testing"; import { HealthCheckService, TypeOrmHealthIndicator, HealthCheckResult } from "@nestjs/terminus"; import { mock } from "jest-mock-extended"; @@ -63,6 +64,33 @@ describe("HealthController", () => { const result = await healthController.check(); expect(result).toBe(healthCheckResult); }); + + describe("when health checks fail with an error", () => { + const error: ServiceUnavailableException = new ServiceUnavailableException({ + status: "error", + db: { + status: "down", + }, + }); + + beforeEach(() => { + jest.spyOn(healthCheckServiceMock, "check").mockImplementation(() => { + throw error; + }); + }); + + it("throws generated error", async () => { + expect.assertions(4); + try { + await healthController.check(); + } catch (e) { + expect(e).toBeInstanceOf(ServiceUnavailableException); + expect(e.message).toBe("Service Unavailable Exception"); + expect(e.response).toEqual(error.getResponse()); + expect(e.stack).toEqual(error.stack); + } + }); + }); }); describe("beforeApplicationShutdown", () => { diff --git a/packages/api/src/health/health.controller.ts b/packages/api/src/health/health.controller.ts index d1a5db6640..a3b3509fe1 100644 --- a/packages/api/src/health/health.controller.ts +++ b/packages/api/src/health/health.controller.ts @@ -22,7 +22,12 @@ export class HealthController implements BeforeApplicationShutdown { @Get() @HealthCheck() public async check(): Promise { - return await this.healthCheckService.check([() => this.dbHealthChecker.pingCheck("database")]); + try { + return await this.healthCheckService.check([() => this.dbHealthChecker.pingCheck("database")]); + } catch (error) { + this.logger.error({ message: error.message, response: error.getResponse() }, error.stack); + throw error; + } } public async beforeApplicationShutdown(signal?: string): Promise {