Start learning free

LESSON 143 OF 173 · BACKEND: TESTS AND RUNNING IT

A Health Check in C#

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, running a query throws an exception, like an InvalidOperationException for a closed connection or a SqliteException for a broken query. Put the risky line in a try block, and when it throws, C# jumps to the catch part instead of crashing; catch (Exception) catches every kind. For example, in a route that reads a quantity:

int quantity;
try {
    quantity = int.Parse(text);
} catch (FormatException) {
    return Results.Json(new { error = "quantity must be a number" }, statusCode: 400);
}

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  (empty)
(the database answers again)
GET /health  →  200  {"database": "ok", "status": "ok"}

Your task: add GET /health, which asks the database SELECT 1 and answers new { status = "ok", database = "ok" }, or "down" for the database when the query throws. Then write the test "health", which checks the status code and the whole text of the answer. 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 the catch follows its closing brace: } catch (Exception) {. The text the test reads is exactly what the shop sends, {"status":"ok","database":"ok"}: status first, no spaces. A test that checks only the 200 lets the typo copy through.


STEP 1 OF 10
    Ctrl + Enter to check

    Ops Health in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free