Start learning free

LESSON 26 OF 173 · BACKEND: YOUR FIRST API

One Way to Send Errors

Practice

Your shop sends errors from six places, and each one builds new { error = ... } by hand. A client relies on every error having the same shape: it reads the message under the key "error". One typo in one place, like eror, and the client loses that message.

The fix is a helper function: an ordinary local function, not tied to any path, that builds the answer in one place. It isn't a route; the routes call it and return what it gives them. It returns an IResult, which carries both the body and the status, and the route passes it on to ASP.NET. A helper for success answers could look like this (not part of the shop):

IResult Created(JsonElement item) {
    return Results.Json(item, statusCode: 201);
}

app.MapPost("/notes", (JsonElement note) => {
    notes.Add(note);
    return Created(note);
});

The answers stay exactly the same; only the code gets tidier. The requests and answers your code must give, in this order:

GET /products/9  →  404  {"error": "Product not found"}
POST /products  {"price": 5, "category": "kitchen"}
  →  400  {"error": "Name is required"}
POST /products  {"name": "Cup", "price": -1, "category": "kitchen"}
  →  400  {"error": "Price must be a whole number of 0 or more"}
DELETE /products/9  →  404  {"error": "Product not found"}
PUT /products/9  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  404  {"error": "Product not found"}
PATCH /products/9  {"price": 5}  →  404  {"error": "Product not found"}
POST /products  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  201  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}
GET /products/5  →  200  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}

Your task: write ErrorResponse(string message, int status), which returns an IResult: the JSON body {"error": message} with the given status. Use it for every error answer in the shop: the 404 of the GET, DELETE, PUT and PATCH routes for /products/{id:int}, and the two 400s of the POST route.


Assignment
Follow the Coding Tutorial to write the ErrorResponse helper and send every error through it.


Hint
The helper goes under shop, outside every route. In each route, write return ErrorResponse(...);: a route's lambda must return an answer on every path, or C# won't compile the file.


STEP 1 OF 8
    Ctrl + Enter to check