Start learning free

LESSON 157 OF 173 · BACKEND: BACKEND WITH AI

The AI Forgot the Missing Case in Java

Practice

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

@GetMapping("/products/{productId}")
Object getProduct(@PathVariable int productId) {
    List<Map<String, Object>> rows = db.queryForList("SELECT * FROM products WHERE id = ?", productId);
    Map<String, Object> row = rows.get(0);
    return Map.of("name", row.get("name"), "price", row.get("price"), "in_stock", (int) row.get("stock") > 0);
}

It works for every product that exists. But when no product has the id, queryForList gives an empty list, and rows.get(0) throws an IndexOutOfBoundsException. Spring answers 500 Internal Server Error. 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 map:

@GetMapping("/coupons/{couponCode}")
Object getCoupon(@PathVariable String couponCode) {
    Map<String, Object> coupon = COUPONS.get(couponCode);
    if (coupon == null) {
        return ResponseEntity.status(404).body(Map.of("error", "Coupon not found"));
    }
    return coupon;
}

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 getProduct. Ask the database for the rows with this id. If the list is empty, answer {"error": "Product not found"} with 404; otherwise answer the first row's name, its price and in_stock (true when the stock is above 0).


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


Hint
queryForList gives an empty list when no row matches. Check rows.isEmpty() before rows.get(0) runs, and answer the error with ResponseEntity.status(404).body(...).


STEP 1 OF 5
    Ctrl + Enter to check

    Ai Missing 404 in Java

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