Skip to content

Commit

Permalink
fix: add log for failed api health / ready check
Browse files Browse the repository at this point in the history
  • Loading branch information
vasyl-ivanchuk committed Apr 23, 2024
1 parent b8391c5 commit ebad24e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
28 changes: 28 additions & 0 deletions packages/api/src/health/health.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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", () => {
Expand Down
7 changes: 6 additions & 1 deletion packages/api/src/health/health.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ export class HealthController implements BeforeApplicationShutdown {
@Get()
@HealthCheck()
public async check(): Promise<HealthCheckResult> {
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<void> {
Expand Down

0 comments on commit ebad24e

Please sign in to comment.