So far, the Kladde answers errors in three different ways. A contact without a name gets 400 with a JSON of its own ({"errors":[…]}), an unknown number gets 404 without any content, and an exception somewhere in the code becomes a 500 that tells the caller nothing or, in development, a page with the whole stack trace. A program that uses the Kladde has to write code of its own for each of these forms.

There is a standard for this: ProblemDetails, described in RFC 9457. In this lesson, you bring every error response of the Kladde into this form. Expected errors, which your Result<T> from K1 reports, become 400, 404 or 409 with their code. Unexpected ones become 500, without telling the caller anything about the inside of the app.

An error response according to the standard

A response according to RFC 9457 has the content type application/problem+json and a JSON object with fixed fields:

JSON
{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
  "title": "Not Found",
  "status": 404,
  "detail": "There is no contact with number 7.",
  "instance": "/api/contacts/7",
  "codes": ["contact.unknown"]
}
Field Meaning
type an address that identifies the kind of problem; ASP.NET Core inserts the section of the HTTP standard for the status code
title a short summary that is always the same for the same kind
status the status code, once more in the content, so that it is preserved if someone passes the response on
detail an explanation of exactly this case, for people
instance where the problem occurred, often the path

All fields are optional. In addition, a response may have fields of its own, the extensions. The Kladde uses one: codes, the error codes from ErrorCodes, exactly the list that used to be in ErrorResponse. A program checks status and codes; a person reads title and detail.