Start learning free

LESSON 143 OF 173 · BACKEND: TESTS AND RUNNING IT

A Health Check

Practice

A shop on a server can stop working while you sleep. A monitoring service notices it for you: every minute it asks the shop a simple question over HTTP, and alerts you when the answer is wrong or doesn't come. The question is a health check, a route made only for this. A good one really asks the parts the shop needs, like its database, and says which one is down.

Asking can fail: when the database can't answer, JdbcTemplate throws a DataAccessException. Put the risky line in a try { } block, and when it throws, Java jumps to the catch part that names the exception instead of crashing. For example, in a route that reads a quantity:

int quantity;
try {
    quantity = Integer.parseInt(text);
} catch (NumberFormatException e) {
    return ResponseEntity.badRequest().body(Map.of("error", "quantity must be a number"));
}

The cheapest question for a database is SELECT 1: it reads no table and just answers 1. While the database is down, the health check still answers 200 with status ok, because the shop itself answers; its database part tells you where to look.

The check plays the monitor, stops the database for a minute, then lets it answer again:

GET /health  →  200  {"database": "ok", "status": "ok"}
(the database stops answering)
GET /health  →  200  {"database": "down", "status": "ok"}
GET /products/count  →  500  (an HTML error page)
(the database answers again)
GET /health  →  200  {"database": "ok", "status": "ok"}

Your task: add GET /health, a method health that asks the database SELECT 1 with db.execute and returns Map.of("status", "ok", "database", "ok"), or "down" for the database when a DataAccessException is thrown. Then write testHealth in HealthTests, which checks the status code and the whole JSON body. The check runs it on the shop, where it must pass, and on a copy whose health query has a typo, so it always says down, where it must fail.


Assignment
Follow the Coding Tutorial to build the /health route and a test that checks its whole answer.


Hint
The query goes inside try { }, and } catch (DataAccessException e) { follows it. A test that checks only the 200 lets the typo copy through: compare response.getBody() too.


STEP 1 OF 11
    Ctrl + Enter to check