Skip to content

Module 04 · Lesson 4.5

Error Handling and Backend Review

40 minUpdated 19 Nov 2026Part of Data Modeling, APIs and Backend · New Project Creation
On this page
  1. What you will learn
  2. Expected and unexpected failures
  3. One central error mapper
  4. A safe 500 with a reference id and a clean log
  5. Review generated backend code against your criteria
  6. Step-by-step workflow
  7. What the assistant does in a review
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

When a kitchen has a problem, a good waiter says: 'Sorry, we cannot serve that now. Here is a table number if you need to ask again.' A bad one reads out the chef's accident report. Your backend should behave like the good waiter.

In this lesson you finish the Tidewell backend. You route every failure through one mapper, return a safe 500 with a short reference id and write a log line that holds no personal data. Then you review generated backend code against your requirements and write a review note about what you changed.

What you will learn

  • Map every kind of failure to a predictable response with the right status code.
  • Return a safe 500 response with a reference id, and write an internal log line without personal data.
  • Review generated backend code with a checklist, including code that adds endpoints nobody asked for.
  • Write a short review note that records what you changed, removed and left open.

Before you start

  • Completed Implementing Endpoints with Validation, or have a small backend of your own.
  • Access to any capable AI assistant.
  • Optional: Node.js and the project from earlier lessons, if you want to run the examples.

Expected and unexpected failures

Some failures are part of normal life. A patient sends a bad slot id, or picks a slot someone else just took. These are expected failures. The system knows what happened and can say what to do next.

Others are surprises: the database is unreachable, or there is a bug. These are unexpected failures. The system does not know what went wrong, and the caller cannot fix it. Each kind gets a different treatment.

FailureKindStatusThe caller seesThe team sees
Malformed inputExpected400The field and how to fix it.Nothing, or a count.
Not found, or not yoursExpected404'We could not find that.'Nothing.
Slot already takenExpected409Choose another time.Nothing.
Inside the notice periodExpected422The clinic's phone number and hours.Nothing.
Database down, or a bugUnexpected500A generic message and a reference id.A log line with the same id.

One central error mapper

If every handler decides for itself how to report errors, they will do it five different ways, and one will forget. The fix is to have one function that turns any failure into a response. Handlers throw. The mapper answers.

First, the known errors. Each one is a small factory that builds an ApiError carrying a complete problem.

TypeScriptsrc/lib/problem.ts (the known problems)
export interface Problem {
  type: string;
  title: string;
  status: number;
  detail: string;
  errors?: FieldError[];
}

const PROBLEM_BASE = "https://tidewell.example/problems/";

export class ApiError extends Error {
  constructor(readonly problem: Problem) {
    super(problem.detail);
  }
}

function fail(code: string, status: number, title: string, detail: string, errors?: FieldError[]): ApiError {
  return new ApiError({ type: PROBLEM_BASE + code, title, status, detail, ...(errors ? { errors } : {}) });
}

export const invalidRequest = (errors: FieldError[]) =>
  fail("invalid-request", 400, "Invalid request", "The request has problems. See errors for details.", errors);

export const notFound = () => fail("not-found", 404, "Not found", "We could not find that.");

export const slotTaken = () =>
  fail("slot-taken", 409, "Slot already taken", "Someone else has just booked this slot. Please choose another time.");

export const noticePeriod = () =>
  fail(
    "notice-period",
    422,
    "Too close to the appointment time",
    `Online changes need at least ${NOTICE_PERIOD_HOURS} hours of notice. Please phone the clinic on 01632 960 123, Monday to Friday, 8:00 to 18:00.`,
  );
  • Problem is the shape from the contract: type, title, status, detail and an optional errors list.
  • ApiError is an ordinary error that carries a ready-made problem. Throwing one is how code says 'this is an expected failure'.
  • fail builds the problem once, so type always starts with the same base and the errors field appears only when there are field errors.
  • The 422 factory reads the 24 from the notice-period rule, so the message and the rule cannot disagree. The phone number and opening hours are the clinic's, as confirmed in Module 1.

Then the mapper itself, with the function that writes the response.

TypeScriptsrc/lib/problem.ts (the mapper)
export function problemResponse(problem: Problem): Response {
  return new Response(JSON.stringify(problem), {
    status: problem.status,
    headers: { "Content-Type": "application/problem+json" },
  });
}

export interface ErrorContext {
  route: string;
  log: (line: string) => void;
  newRef: () => string;
}

// The central mapper: known errors keep their own problem, everything else becomes a safe 500.
export function errorResponse(error: unknown, ctx: ErrorContext): Response {
  if (error instanceof ApiError) return problemResponse(error.problem);

  const ref = ctx.newRef();
  const dbCode = (error as { code?: unknown } | null)?.code;
  ctx.log(
    JSON.stringify({
      level: "error",
      ref,
      route: ctx.route,
      errorName: error instanceof Error ? error.name : typeof error,
      dbCode: typeof dbCode === "string" ? dbCode : undefined,
    }),
  );
  return problemResponse({
    type: PROBLEM_BASE + "internal-error",
    title: "Something went wrong",
    status: 500,
    detail: `We could not complete your request. If you phone the clinic, please quote reference ${ref}.`,
  });
}
  • problemResponse writes the JSON body and the application/problem+json content type.
  • errorResponse first checks error instanceof ApiError. If so, the error is expected and its own problem is returned unchanged.
  • Anything else is unexpected. The mapper makes a reference id, writes one log line and returns a 500 with a generic message.
  • log and newRef are passed in, so tests can capture the line and fix the id. In the real app they write to your logging system and make a short random id.

A safe 500 with a reference id and a clean log

A reference id is like the ticket number a help desk gives you. The patient quotes it. You search your logs for the same number and find the real cause. They get a way to ask for help, and you get a way to find the fault, without anyone seeing the guts of the system.

The test below makes the database fail in a realistic way. The error message it throws contains a patient's email address, exactly as a real duplicate-key error would. Then it checks whether that address escapes into the response or the log.

TypeScripttest-errors.ts (the failing database)
// A database that fails the way a real one can: its message contains a patient's email address.
const failingDb: Db = {
  async query() {
    throw Object.assign(
      new Error('duplicate key value violates unique constraint "patients_email_key" Key (email)=(patient.a@example.com) already exists.'),
      { code: "23505", constraint: "patients_email_key" },
    );
  },
};

const logs: string[] = [];
const deps: Deps = { db: failingDb, now: () => NOW, patientId: 1, log: (line) => logs.push(line), newRef: () => "K7QX-29PD" };

const request = new Request("http://localhost/api/bookings", { method: "POST", body: '{"slotId":2}' });
const response = await handleCreateBooking(request, deps);
TypeScripttest-errors.ts (what it prints)
console.log("response:", response.status, response.headers.get("content-type"));
const body = await response.text();
console.log(body);
console.log("internal log:");
console.log(logs.join("\n"));
console.log("email appears in response or log:", (body + logs.join("")).includes("example.com"));
The 500 response, the internal log line and the leak checkCaptured from a real run
response: 500 application/problem+json
{"type":"https://tidewell.example/problems/internal-error","title":"Something went wrong","status":500,"detail":"We could not complete your request. If you phone the clinic, please quote reference K7QX-29PD."}
internal log:
{"level":"error","ref":"K7QX-29PD","route":"POST /api/bookings","errorName":"Error","dbCode":"23505"}
email appears in response or log: false
  • The caller gets a status of 500, the problem content type, a generic title and a detail sentence that holds only the reference id.
  • The log line has the same id, the route, the kind of error (Error) and PostgreSQL's error code (23505). That is enough to start looking.
  • The email address is in the error message, and the message is left out of both places. The last line shows the check: false means it did not escape.

Note that the code 23505 reached the mapper because the constraint name was not 'one_live_booking_per_slot'. The service only turns that one index into a 409. A unique violation anywhere else is a surprise, so it becomes a 500.

What to log, and what to leave out

Log thisNever log this
A reference id and the time.Names, emails, phone numbers or other personal data.
The route and the kind of error.Request bodies or full database messages, which may hold values.
The database error code.Passwords, keys, session tokens or connection strings.
Which release was running.Stack traces in the response. Keep them in the log store, with the same access care.
A log line is a record that many people can read, and it is kept for a long time. Treat it like a database table of personal data.

The kit logs a line of JSON. In a real app you would use your logging tool and restrict who can read the logs. See OWASP's Logging Cheat Sheet (opens in a new tab) for more.

One more expected failure comes from the handler itself: a body that is not valid JSON. It is a 400, not a 500, because it is the caller's mistake.

TypeScripttest-errors.ts (unreadable JSON)
const broken = await handleCreateBooking(new Request("http://localhost/api/bookings", { method: "POST", body: "{oops" }), deps);
console.log("bad JSON:", broken.status, await broken.text());
Expected outputCaptured from a real run
bad JSON: 400 {"type":"https://tidewell.example/problems/invalid-request","title":"Invalid request","status":400,"detail":"The request has problems. See errors for details.","errors":[{"field":"body","message":"The body must be valid JSON."}]}

Review generated backend code against your criteria

Generated code is unreviewed code. It often runs and looks tidy. The risks are the things it did that you did not ask for. Here is a draft an assistant might add to the Tidewell backend, in the middle of a task about bookings.

TypeScriptreview-sample.ts (a generated draft: do not use)
// A generated draft, kept exactly as an assistant might return it. DO NOT USE: it is the review example.
import type { Db } from "./db";

export async function exportPatients(db: Db): Promise<Response> {
  try {
    const { rows } = await db.query("SELECT * FROM patients");
    return Response.json(rows);
  } catch (error) {
    return Response.json({ error: (error as Error).message }, { status: 500 });
  }
}

It is short and it compiles. Now run it, once with a working database and once with a failing one.

What the draft does (real output)Captured from a real run
200 [{"id":1,"full_name":"Patient A","email":"patient.a@example.com","phone":"01632 960001"},{"id":2,"full_name":"Patient B","email":"patient.b@example.com","phone":"01632 960002"}]
500 {"error":"permission denied for table patients (user \"app_user\", host 10.0.0.5)"}

Every patient's name, email and phone leave the system in one call. The failing case then hands the caller the database user and the server address. Apply the checklist below.

CheckQuestionFinding for the draft
ScopeWhich requirement or scenario asks for this?None. An export of all patients is not in the list.
AccessWho may call it, and where is that checked?Anyone. There is no sign-in or role check.
DataDoes it return only what the requirement needs? (CON-01)SELECT * returns every column of every row.
ContractIs it in the OpenAPI file?No. It would be a hidden endpoint, so nobody tests it.
InputIs every input validated on the server?It takes none, but a real version would need limits and paging.
SQLDoes every query use parameters?Yes here, but check each query in other drafts.
ErrorsDoes any response include raw error text?Yes: the message is sent to the caller.
LogsDoes it log anything with personal data?It logs nothing at all, so a failure cannot be traced.
TestsWhich criterion does a test prove?None. There is no scenario to test.

The decision is simple. Remove the endpoint. If the clinic really needs an export, it becomes a candidate requirement with a source, a permission rule for the roles that may use it and criteria. Hiding it from the contract is the worst option, because it stays reachable.

Trace the acceptance scenarios to tests

ScenarioTest step in test-api.tsResult
FR-02.1 Cancel outside the notice periodStep 6: cancel at exactly 24 hours200, status cancelled
FR-02.2 Cancel inside the notice periodStep 5b: cancel at 23 hours422, booking unchanged
FR-02.3 Someone else's bookingStep 4: patient B cancels A's booking404, nothing revealed
NFR-01 One live booking per slotStep 3: second patient books the same slot409 slot-taken
FR-05 Changes are recordedbooking_changes rows after the callsTwo creations, one cancellation
If a Must requirement has no row here, it has no proof.

Write the review note

A review note is the short record the module assignment asks for. It says what you checked and what you did about it, so the next person does not have to repeat the work. It is plain text kept next to the code.

Markdowndocs/reviews/2026-11-19-bookings-backend.md
# Review note: bookings backend, first draft

Date: 2026-11-19. Reviewer: (your name). Assistant used: (tool name).

## Asked for
POST /api/bookings and POST /api/bookings/{bookingId}/cancel (FR-01, FR-02).

## Changed
- Replaced error text in responses with the problem format and a reference id.
- Added the patient id to the booking lookup, so other people's bookings give 404 (FR-02.3).
- Moved the 24-hour rule into rules.ts with a comment that points to the decision.

## Removed
- GET /api/export-patients. No requirement, no permission rule, returned all personal data.

## Kept as it was
- Parameterised SQL and the single-statement write of a booking and its history row.

## Open decisions
- Should staff be able to export patient data? Owner: clinic owner. Not built until a requirement exists.

## Checks run
- Five scenario tests pass (FR-02.1, FR-02.2, FR-02.3, NFR-01, FR-05).
- A failing database gives a 500 with a reference id, and no email appears in the response or the log.

An example of the note's shape, written for the draft above.

Step-by-step workflow

  1. Step 1: List what changed

    Write down every endpoint, table and file the assistant added or changed. Compare with what you asked for.

    What you should see: A list where each item is 'asked for' or 'not requested'.

  2. Step 2: Map each item to a requirement

    Give every endpoint and table a requirement ID and a scenario. Items with neither go on the remove list.

    What you should see: A trace with no orphans.

  3. Step 3: Read for security

    Check who can call each endpoint, whether every input is validated, whether every query has parameters and whether any response shows raw error text.

    What you should see: A list of findings by endpoint.

  4. Step 4: Make failures happen

    Break the database on purpose, send malformed JSON and try another patient's booking. Read the status and the body of each answer.

    What you should see: Every failure gives the response in the contract.

  5. Step 5: Trace scenarios to tests

    Fill the trace table. A scenario without a test gets a new test before you move on.

    What you should see: Every Must scenario has a passing test.

  6. Step 6: Write the review note

    Record what you changed, removed, kept and left open, with the date and tools used. Commit it with the code.

    What you should see: A review note in the repository.

Reviewing generated backend code
  1. List changes

    Asked for or not

  2. Trace to requirements

    Orphans out

  3. Security read

    Access, input, SQL, errors

  4. Force failures

    Read the responses

  5. Scenario tests

    One per Must

  6. Review note

    Committed with the code

Remove first, fix second, prove third, record last.

What the assistant does in a review

An assistant makes a useful second reviewer, as long as it is given your requirements and criteria. It is a poor judge of what your clinic needs, and it often approves its own work.

TaskAssistant's partYour part
Find unrequested codeLists every endpoint and table against the requirements you paste.Decide to remove each, or to file it as a candidate.
Review error handlingPoints out raw error text and missing status codes.Check each finding against the contract.
Spot security risksFlags missing access checks and string-built SQL.Confirm each one in the code. Do not rely on its summary.
Suggest testsProposes failure cases to try.Run them and read the real responses.
Write the review noteDrafts the structure from your list.Make sure it states only what you checked.

Conclusion and your next step

Predictable failures come from one mapper. Expected errors keep their own problem, and anything else becomes a generic 500 with a reference id and a log line that holds no personal data. Reviewing generated code means looking for what nobody asked for, then proving the rest with tests and writing down what you did.

Your next step: finish the Backend for the capstone assignment for this module, including the review note. Then move on to Frontend and API Integration, where you build screens on top of this API, starting with Planning Screens from Workflows.

For more on reviewing code, see the AI-Generated Code Review Checklist and How to Prevent AI Hallucinations in Code Generation. To revisit the whole module, open Data Modeling, APIs and Backend.

Reusable prompt

Backend code review against criteria

Asks for review findings on pasted backend code, checked against requirements and criteria, with unrequested code listed separately.

You are reviewing backend code. Report findings only. Do not rewrite the code and do not approve it.

Fictional clinic: Tidewell Physiotherapy. Out of scope: payments, insurer billing, clinical notes. Patient data must stay minimal.

Requirements and criteria:
FR-02 A patient can move or cancel their own booking. FR-02.1 outside the notice period it is cancelled. FR-02.2 inside the notice period it is unchanged and the patient is told to phone the clinic. FR-02.3 someone else's booking is unchanged and its existence is not revealed.
FR-05 Every change records who and when.
Errors use problem details: 400 invalid-request, 404 not-found, 409 slot-taken, 422 notice-period, 500 internal-error with a short reference id and no internal details.

Code to review:
[paste the generated route handlers and service here]

Tasks:
1. List every endpoint and table in the code, and the requirement it serves. Put the ones with no requirement under "Not requested".
2. List security findings: missing access checks, unvalidated input, SQL built from strings, personal data returned or logged.
3. List responses that expose internal details, such as stack traces, SQL text or table names.
4. List acceptance scenarios that have no test.
5. For each finding, say what to check in the code to confirm it.
Show the reusable template

Replace each {{placeholder}} with your own details.

You are reviewing backend code. Report findings only. Do not rewrite the code and do not approve it.

Context: {{organisation_scope_and_data_rules}}.

Requirements and criteria:
{{requirements_and_acceptance_criteria}}
Errors use {{error_format_and_rules}}.

Code to review:
{{code}}

Tasks:
1. List every endpoint and table in the code, and the requirement it serves. Put the ones with no requirement under "Not requested".
2. List security findings: missing access checks, unvalidated input, SQL built from strings, personal data returned or logged.
3. List responses that expose internal details, such as stack traces, SQL text or table names.
4. List acceptance scenarios that have no test.
5. For each finding, say what to check in the code to confirm it.

Expected output and limitations

A findings list in five parts: endpoints and tables with their requirements, security findings, responses that leak details, scenarios without tests and how to confirm each finding in the code.

Sample responseIllustrative — your output will differ
1. Endpoints and tables
   POST /api/bookings -> FR-01, FR-02
   POST /api/bookings/{bookingId}/cancel -> FR-02
   Not requested: GET /api/export-patients

2. Security
   export-patients has no access check and returns every column of every patient.
   Confirm: search for the route and read its handler.

3. Leaks
   The catch block in export-patients returns error.message to the caller.
   Confirm: trigger a failure and read the response body.

4. No test
   FR-05 (change history) has no test that reads booking_changes.

5. Confirm by
   Run the scenarios and compare the statuses with the contract.

Limitations to keep in mind

  • It can only review the code you paste. Files you did not share stay unchecked.
  • Some findings will be wrong and some real problems will be missed. Confirm each one in the code and with a test.
  • It cannot say whether a rule is the clinic's rule. Policy questions go to the named role.

Common errors and how to fix them

The response to a failure includes the database error text.

Why it happens: The catch block returned error.message, which was convenient while debugging.

Fix: Send every unexpected error to the central mapper, which returns a generic 500 and a reference id.

Logs contain emails, names or request bodies.

Why it happens: Whole objects were logged to make debugging easier.

Fix: Log a reference id, the route, the kind of error and the database code only. Review log lines like data tables.

An endpoint that no requirement asks for ships with the feature.

Why it happens: The assistant added it and nobody traced the code back to the requirements.

Fix: Map every endpoint and table to a requirement and a scenario. Remove the ones with neither, or file them as candidates.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Review a generated Ferngate backend

An assistant produced a draft for Ferngate Cycle Repairs. Review it with the checklist and write a review note that says what you would change, remove and leave open.

You will need

  • Requirement: a mechanic can record a part taken for a job.
  • Draft: POST /api/jobs/{jobId}/parts-used records a part. GET /api/parts/export lists every part with its supplier price and the owner's reorder notes. DELETE /api/parts removes all parts that have no stock. The catch block returns the error message and the SQL text.
  • Note: the owner has not decided what happens when a mechanic records an out-of-stock part.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • Which endpoint could destroy data? Which one could expose business information?
  • Think about what the mechanic, the owner and the person fixing a fault each need to see after a failure.
Show a model answer

A strong answer keeps the parts-used endpoint, because the requirement asks for it. It removes the delete-all endpoint, since a bulk deletion has no requirement and could destroy records, and it puts the export in the candidate list with a source and a permission rule, because price and reorder notes are business-sensitive. The error finding says to return a generic problem with a reference id and to log the id, route, error kind and database code, without the SQL text. The out-of-stock case is left open for the owner. The checks include a forced database failure, an attempt to call the removed routes and a test per scenario.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.What should a 500 response contain?
    Show the answer and explanation

    Answer: B. The caller cannot fix an internal fault, and details help attackers. A reference id lets the team find the real cause in the logs. The stack trace and database text are tempting for debugging, but they leak how the system works and may contain personal data.

  2. 2.A generated 'export all patients' endpoint has no requirement. What do you do?
    Show the answer and explanation

    Answer: B. Unrequested code is unreviewed scope, and this one exposes personal data. An obscure address is tempting, but secrecy is not access control, and the endpoint stays reachable and untested.

  3. 3.Which log line is acceptable for an unexpected failure?
    Show the answer and explanation

    Answer: B. The second gives enough to start investigating and holds no personal data. The request body and database messages are tempting because they carry more detail, but they can include emails, names or other values.

Frequently asked questions

Why should I not show users the real error message?

The real message describes how your system works, and it can contain private values such as an email address. Users cannot fix it, but an attacker can learn from it. Show a calm, generic message and keep the details in your own logs.

What is a reference id in an error response?

It is a short code that appears both in the error the user sees and in your internal log. When a user reports it, you search the logs for the same code and find the cause. It works like the ticket number at a help desk.

What should I never write to a log?

Never log passwords, keys, tokens or personal data such as names, emails and phone numbers. Be careful with request bodies and database error messages, because both can carry real values. A reference id, the route, the kind of error and an error code are usually enough.

How do I review code written by an AI assistant?

Start by listing everything it added and checking that each item has a requirement. Then read for access checks, input validation, parameterised SQL and error text, and make failures happen on purpose. Back each finding with a test, and write down what you changed.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.