Start learning free

LESSON 157 OF 173 · BACKEND: BACKEND WITH AI

The AI Forgot the Missing Case

Practice

An AI assistant wrote the product page for this shop. Its MapGet function asks the database for one product and answers its name, its price and whether it is in stock. Here is the AI's version:

app.MapGet("/products/{id}", (int id) => {
    var cmd = db.CreateCommand();
    cmd.CommandText = "SELECT * FROM products WHERE id = $id";
    cmd.Parameters.AddWithValue("$id", id);
    using var row = cmd.ExecuteReader();
    row.Read();
    return Results.Json(new { name = row["name"], price = row["price"], in_stock = (long)row["stock"] > 0 });
});

It works for every product that exists. But when no product has the id, row.Read() gives false: there is no row to read, and row["name"] throws an InvalidOperationException. ASP.NET answers 500 Internal Server Error with an empty body. The AI wrote the happy path and forgot the missing case.

The fix is a check that runs before the code uses the value. Here it is on another route, for coupons kept in a dictionary:

app.MapGet("/coupons/{code}", (string code) => {
    if (!COUPONS.ContainsKey(code)) {
        return Results.Json(new { error = "Coupon not found" }, statusCode: 404);
    }
    return Results.Json(COUPONS[code]);
});

A 404 says "there is no such thing", in JSON the client can read. Your code must give these answers:

GET /products/1   →  200  {"name": "Mug", "price": 12, "in_stock": true}
GET /products/2   →  200  {"name": "Notebook", "price": 7, "in_stock": false}
GET /products/8   →  200  {"name": "Gift card", "price": 50, "in_stock": true}
GET /products/99  →  404  {"error": "Product not found"}
GET /products/0   →  404  {"error": "Product not found"}

Your task: rewrite the MapGet function. Ask the database for the product with this id. If row.Read() finds no row, answer {"error": "Product not found"} with 404; otherwise answer its name, its price and in_stock (true when the stock is above 0).


Assignment
Follow the Coding Tutorial to rewrite the MapGet function with the missing case handled.


Hint
row.Read() moves to the first row and gives false when there is none. Use what it gives in an if before any line reads row["..."], and add statusCode: 404 after the error object.


STEP 1 OF 7
    Ctrl + Enter to check