Part II — Intermediate Development · Chapter 6 · Lesson 1 of 5 · 10 min read
Lesson 1: Failure Categories and Useful Error Messages
Lesson level: Intermediate
Purpose: Classify failures accurately and design diagnostic messages that help users correct problems without exposing sensitive implementation details.
Learning objectives
By the end of this lesson, you should be able to:
- distinguish lexical, parsing, static, runtime, permission, resource, network, and host failures;
- use standard error categories consistently;
- separate an error category, code, message, location, cause, and context;
- write actionable messages that identify what failed and how to respond;
- preserve useful source and stack information when available;
- avoid leaking secrets or unsafe internal details;
- map internal failures to stable boundary responses; and
- test diagnostics as part of the program contract.
1.1 Errors are part of the interface
A program is not complete merely because its successful path works. Users, tools, hosts, and operators also experience its failures. A diagnostic is therefore part of the interface: it should identify the problem, locate it when possible, preserve useful cause information, and support a safe next action.
A vague message such as Something went wrong hides the distinction between malformed source, invalid data, denied permission, exhausted resources, unavailable dependencies, and host defects. Classification narrows the investigation immediately.
1.2 Failure stages
| Stage | Question | Typical failure |
|---|---|---|
| Lexing | Can the source characters form tokens? | Unexpected character or unterminated string |
| Parsing | Do the tokens form valid program structure? | Missing delimiter or unexpected token |
| Static checking | Does the source satisfy known semantic rules? | Undefined name or duplicate declaration |
| Runtime evaluation | Can this valid program execute with these values? | Division by zero or invalid index |
| Host boundary | Can the host convert, authorize, and invoke the operation? | Unsupported value or missing export |
| External operation | Did the registered dependency complete correctly? | Network, permission, timeout, or host failure |
1.3 Standard error categories
PeaLang defines these standard categories:
- SyntaxError — malformed lexical or grammatical structure;
- TypeError — an operation receives incompatible values;
- NameError — a required name cannot be resolved;
- ImportError — a module cannot be resolved or loaded;
- IndexError — a sequence position is outside its valid range;
- KeyError — a required map key is absent;
- ValueError — the value category is acceptable, but its content or range is not;
- PermissionError — the requested capability is not authorized;
- TimeoutError — the operation exceeds its deadline;
- ResourceLimitError — an instruction, memory, stack, output, collection, or other budget is exhausted;
- NetworkError — a network operation fails; and
- HostError — the embedding application or registered host operation fails.
1.4 SyntaxError
Use SyntaxError when source text cannot be interpreted as a valid program. Examples include an unsupported character, an open quoted string, an unterminated block, a missing expression, or a misplaced token.
pricing.pea:12:18: SyntaxError P001: Expected }, got end of file
The message states the expected structure and the observed condition. A source range should point as close as possible to the place where the parser recognized the problem, while the user should also inspect the immediately preceding construct.
1.5 TypeError
Use TypeError when an operator, call, or assignment receives a value of an incompatible kind.
rules.pea:8:22: TypeError T104: Operator + cannot combine a number and a map
Avoid vague wording such as bad operand. Name the operation and the value categories involved. Do not print entire sensitive values merely to explain their types.
1.6 NameError and ImportError
NameError indicates that a variable, function, or other binding cannot be resolved. When a close suggestion is available, present it as a hint rather than silently changing the source.
rules.pea:7:14: NameError N101: Undefined name subtotal; did you mean subtotl?
ImportError identifies a module-resolution or loading failure. Include the requested logical module and safe source context, but avoid exposing private search paths or credentials.
1.7 IndexError and KeyError
IndexError applies to an invalid sequence position. A useful message includes the requested index and collection length when that information is safe.
scores.pea:10:9: IndexError C201: Index 4 is outside a list of length 4
KeyError applies when a required map key is absent. If absence is expected and modeled through null or validation, handle it as data rather than allowing an exception. Reserve KeyError for an access that requires the key to exist.
1.8 ValueError
ValueError means the general kind of value is acceptable but the specific content is not. A number outside an approved range, an unsupported category string, or a zero divisor supplied to a contract can be a value failure.
case.pea:5:1: ValueError V202: service_impact must be between 0 and 10; received 14
State the constraint, the safe received value when appropriate, and the field or parameter involved.
1.9 PermissionError
PermissionError is a deliberate policy result, not a mysterious runtime defect. Identify the denied capability and the operation that required it without revealing secret configuration.
PermissionError S301: Permission net.http.get is required for host.http.get
Do not recommend enabling every permission. The corrective action is to verify whether the operation is necessary and, if so, grant the narrow documented capability through the host policy.
1.10 TimeoutError and ResourceLimitError
A timeout states that elapsed execution exceeded a deadline. A resource-limit failure states that a defined budget such as instructions, memory, call depth, stack depth, collection items, output bytes, HTTP requests, or file-read bytes was exhausted.
Keep these categories distinct. A timeout may depend on wall-clock conditions, while an instruction limit can remain deterministic for the same execution path.
ResourceLimitError R401: Instruction limit exceeded
TimeoutError R402: Execution deadline exceeded
1.11 NetworkError and HostError
NetworkError represents failure of an authorized network operation: connection failure, unavailable endpoint, invalid response, or exhausted retry policy. A message should identify the logical operation and safe destination context, not credentials or sensitive request content.
HostError represents failure inside the embedding application or a registered host function. Preserve an internal cause for trusted diagnostics, but return a stable, sanitized message across the public boundary.
1.12 The anatomy of a useful diagnostic
| Field | Purpose |
|---|---|
| category | Broad failure family for handling and reporting |
| code | Stable identifier for tests, support, and automation |
| message | Concise human-readable explanation |
| source | Logical file or module identity |
| line and column range | Location associated with the failure |
| cause | Underlying failure when safe and available |
| stack | Relevant call sequence for investigation |
| request or correlation identifier | Connection to logs and operational evidence |
| hint | Optional corrective guidance |
Not every surface should display every field. Developer tools may show source and stack details; a public service may return only a code, sanitized message, and request identifier.
1.13 Message-writing pattern
A strong message answers four questions:
- What failed? Name the operation, field, or construct.
- Why did it fail? State the violated expectation.
- Where did it fail? Supply source or boundary context.
- What should happen next? Give a safe, specific action when one is known.
Example: ValueError V202: affected_users must be a nonnegative integer; validate the input record before scoring.
1.14 Stable codes and evolving prose
Automation should rely on a stable category or code, not exact message punctuation. Human wording may improve over time, while a stable code lets tests, dashboards, and support procedures keep working.
Choose codes from a documented namespace. Do not reuse one code for unrelated failures or create a new code for every dynamic value.
1.15 Preserve causes without leaking them
When one failure wraps another, preserve the cause internally. A host operation may fail because a lower-level network client timed out. Trusted logs can retain the chain, while the public result can report a sanitized NetworkError or TimeoutError.
Never include access tokens, passwords, signing keys, authorization headers, private package URLs, complete sensitive records, or arbitrary host-object representations in messages.
1.16 Source locations and stacks
A source location identifies where a failure was associated with code. A stack identifies the sequence of calls that led there. Both are evidence, not necessarily the complete root cause.
For syntax failures, inspect the reported location and the preceding token. For runtime failures, start at the innermost relevant frame, then trace values and boundary calls outward.
1.17 Validation failures versus exceptional failures
Expected invalid business input can be represented as a structured result when the contract calls for it. For example, an inventory analyzer can return {"valid": false, "reason_code": "INVALID_QUANTITY"} and continue with later records.
Use an exception when ordinary progress cannot continue safely, such as malformed source, missing required module, denied capability, exhausted resource budget, or a host operation that cannot fulfill its contract.
1.18 Boundary mapping
A service or embedding host should map internal errors to stable boundary responses. Preserve the category and request identifier, sanitize the message, and choose an appropriate host-level status without discarding internal evidence.
| Internal category | Boundary treatment |
|---|---|
| SyntaxError or TypeError in supplied extension | Reject compilation or loading with a safe source diagnostic |
| ValueError in request data | Return a validation response with field context |
| PermissionError | Deny the operation without attempting it |
| TimeoutError or ResourceLimitError | Stop execution and report bounded termination |
| NetworkError | Apply the documented retry or availability policy |
| HostError | Return a sanitized failure and preserve internal cause data |
1.19 Observability without disclosure
Operational evidence can include category, code, source identity, safe line and column information, elapsed time, consumed budgets, request identifier, and a sanitized cause chain. Apply retention and access controls appropriate to the data.
Do not turn diagnostic logging into a second unrestricted output channel. The same least-privilege and data-minimization principles apply to logs, traces, and audit records.
1.20 Diagnostic quality checklist
- Is the category accurate?
- Is the code stable and documented?
- Does the message name the failed operation or field?
- Does it state the violated expectation?
- Is source context present when available?
- Is any suggested correction safe and specific?
- Are causes preserved internally?
- Are secrets and sensitive values removed?
- Can automation respond without parsing prose?
- Is the diagnostic tested?
1.21 Common mistakes
- Using one generic category: classification should narrow the investigation.
- Blaming the user: describe the violated contract neutrally.
- Reporting only a symptom: identify the failed expectation when known.
- Exposing raw host exceptions: sanitize public messages and preserve causes internally.
- Embedding secrets in context: redact or omit sensitive data.
- Changing codes casually: stable codes are part of the integration contract.
- Testing exact prose only: assert category, code, location, and essential fields.
- Retrying every error: syntax, validation, and permission failures are not transient.
- Conflating timeout with instruction exhaustion: keep resource dimensions distinct.
1.22 Worked triage examples
| Observation | Classification | First action |
|---|---|---|
| Quoted text reaches end of file | SyntaxError | Inspect the opening quote and surrounding line |
| List position equals list length | IndexError | Review the valid zero-based range |
| Impact is 14 | ValueError | Validate the documented 0–10 range |
| HTTP capability is absent | PermissionError | Confirm necessity and host policy |
| Instruction budget is exhausted | ResourceLimitError | Investigate loops and workload bounds |
| Registered provider throws unexpectedly | HostError | Use the request ID to inspect trusted logs |
1.23 Guided practice
- Classify an unterminated string, missing map key, negative quantity, denied HTTP call, and exhausted instruction budget.
- Rewrite Invalid input as an actionable ValueError message.
- Design a stable code for a missing required inventory field.
- Explain when an invalid record should be a structured result instead of an exception.
- Separate safe public fields from trusted internal diagnostic fields.
- Explain why a timeout should not be reported as a generic HostError.
- Identify sensitive data that must be removed from a network failure.
- Write test assertions that remain valid if message wording changes.
1.24 Hands-on lab: Build a diagnostic catalog
Goal: Create a small PeaLang program and accompanying diagnostic catalog covering the major failure categories.
Required scenarios:
- an unterminated string or block;
- an undefined name;
- an incompatible arithmetic operation;
- an invalid list index;
- a missing required map key;
- a numeric value outside an approved range;
- a denied registered capability described through a host-boundary note;
- a bounded loop that demonstrates resource exhaustion in a controlled test environment;
- a simulated network failure classification; and
- a simulated host-function failure classification.
For each scenario, record stage, category, code, safe message, source context, internal cause if applicable, public response, corrective action, and a regression assertion.
Deliverable: Valid source, temporary defective variants, a diagnostic catalog, expected and actual results, redaction rules, and a short explanation of which failures are retryable.
1.25 Review questions
- Why are errors part of a program’s interface?
- How does a syntax failure differ from a runtime failure?
- When should TypeError be used instead of ValueError?
- What distinguishes KeyError from an optional missing field?
- Why is PermissionError a policy result?
- How do TimeoutError and ResourceLimitError differ?
- What information should a stable diagnostic code provide?
- Why should causes be preserved internally?
- Which fields are appropriate for a public boundary response?
- Why should tests avoid depending only on exact prose?
1.26 Applied challenge
Review the Chapter 5 Inventory Analyzer and design a complete diagnostic contract for it. Classify malformed source, missing fields, invalid values, invalid indices, boundary conversion failures, permission denial, exhausted budgets, and host-operation failures. Add stable codes, safe messages, retry guidance, public mappings, and regression tests without changing successful analysis results.
Lesson summary
Useful diagnostics classify failures accurately, identify the violated expectation, provide safe source or boundary context, preserve internal causes, and support a clear response. Stable categories and codes serve automation, while concise messages serve people. Good error design also minimizes disclosure, distinguishes validation from exceptional failure, and treats permissions and resource limits as explicit runtime policies.
Next lesson: Structured Exception Handling and Recovery
The next lesson introduces try, catch, finally, throw, recovery boundaries, cleanup, reclassification, and the difference between handling a failure and hiding it.
Lesson status: Ready for review.