Module 04 · Lesson 4.5
Error Handling and Backend Review
On this page
- What you will learn
- Expected and unexpected failures
- One central error mapper
- A safe 500 with a reference id and a clean log
- Review generated backend code against your criteria
- Step-by-step workflow
- What the assistant does in a review
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- 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.
| Failure | Kind | Status | The caller sees | The team sees |
|---|---|---|---|---|
| Malformed input | Expected | 400 | The field and how to fix it. | Nothing, or a count. |
| Not found, or not yours | Expected | 404 | 'We could not find that.' | Nothing. |
| Slot already taken | Expected | 409 | Choose another time. | Nothing. |
| Inside the notice period | Expected | 422 | The clinic's phone number and hours. | Nothing. |
| Database down, or a bug | Unexpected | 500 | A 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.
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.`,
);Problemis the shape from the contract: type, title, status, detail and an optional errors list.ApiErroris an ordinary error that carries a ready-made problem. Throwing one is how code says 'this is an expected failure'.failbuilds the problem once, sotypealways starts with the same base and theerrorsfield 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.
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}.`,
});
}problemResponsewrites the JSON body and theapplication/problem+jsoncontent type.errorResponsefirst checkserror 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.
logandnewRefare 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.
// 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);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"));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 this | Never 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. |
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.
const broken = await handleCreateBooking(new Request("http://localhost/api/bookings", { method: "POST", body: "{oops" }), deps);
console.log("bad JSON:", broken.status, await broken.text());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.
// 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.
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.
| Check | Question | Finding for the draft |
|---|---|---|
| Scope | Which requirement or scenario asks for this? | None. An export of all patients is not in the list. |
| Access | Who may call it, and where is that checked? | Anyone. There is no sign-in or role check. |
| Data | Does it return only what the requirement needs? (CON-01) | SELECT * returns every column of every row. |
| Contract | Is it in the OpenAPI file? | No. It would be a hidden endpoint, so nobody tests it. |
| Input | Is every input validated on the server? | It takes none, but a real version would need limits and paging. |
| SQL | Does every query use parameters? | Yes here, but check each query in other drafts. |
| Errors | Does any response include raw error text? | Yes: the message is sent to the caller. |
| Logs | Does it log anything with personal data? | It logs nothing at all, so a failure cannot be traced. |
| Tests | Which 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
| Scenario | Test step in test-api.ts | Result |
|---|---|---|
| FR-02.1 Cancel outside the notice period | Step 6: cancel at exactly 24 hours | 200, status cancelled |
| FR-02.2 Cancel inside the notice period | Step 5b: cancel at 23 hours | 422, booking unchanged |
| FR-02.3 Someone else's booking | Step 4: patient B cancels A's booking | 404, nothing revealed |
| NFR-01 One live booking per slot | Step 3: second patient books the same slot | 409 slot-taken |
| FR-05 Changes are recorded | booking_changes rows after the calls | Two creations, one cancellation |
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.
# 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
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'.
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.
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.
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.
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.
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.
- List changes
Asked for or not
- Trace to requirements
Orphans out
- Security read
Access, input, SQL, errors
- Force failures
Read the responses
- Scenario tests
One per Must
- 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.
| Task | Assistant's part | Your part |
|---|---|---|
| Find unrequested code | Lists every endpoint and table against the requirements you paste. | Decide to remove each, or to file it as a candidate. |
| Review error handling | Points out raw error text and missing status codes. | Check each finding against the contract. |
| Spot security risks | Flags missing access checks and string-built SQL. | Confirm each one in the code. Do not rely on its summary. |
| Suggest tests | Proposes failure cases to try. | Run them and read the real responses. |
| Write the review note | Drafts 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.
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.
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.
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.
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.
- Error Handling Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Guidance on generic error responses and logging the detail internally.
- Logging Cheat Sheet(opens in a new tab)
OWASP · Official documentation · What to record in logs and which data to leave out.
- RFC 9457: Problem Details for HTTP APIs(opens in a new tab)
IETF · Official documentation · The standard behind the problem format used for every error in this module.
- HTTP response status codes(opens in a new tab)
MDN Web Docs · A plain reference for the meaning of each status code.
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.