PeaBox Lab › PeaLang › Learn › Chapter 6 › Lesson 1

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:

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

StageQuestionTypical failure
LexingCan the source characters form tokens?Unexpected character or unterminated string
ParsingDo the tokens form valid program structure?Missing delimiter or unexpected token
Static checkingDoes the source satisfy known semantic rules?Undefined name or duplicate declaration
Runtime evaluationCan this valid program execute with these values?Division by zero or invalid index
Host boundaryCan the host convert, authorize, and invoke the operation?Unsupported value or missing export
External operationDid the registered dependency complete correctly?Network, permission, timeout, or host failure

1.3 Standard error categories

PeaLang defines these standard categories:

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

FieldPurpose
categoryBroad failure family for handling and reporting
codeStable identifier for tests, support, and automation
messageConcise human-readable explanation
sourceLogical file or module identity
line and column rangeLocation associated with the failure
causeUnderlying failure when safe and available
stackRelevant call sequence for investigation
request or correlation identifierConnection to logs and operational evidence
hintOptional 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:

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 categoryBoundary treatment
SyntaxError or TypeError in supplied extensionReject compilation or loading with a safe source diagnostic
ValueError in request dataReturn a validation response with field context
PermissionErrorDeny the operation without attempting it
TimeoutError or ResourceLimitErrorStop execution and report bounded termination
NetworkErrorApply the documented retry or availability policy
HostErrorReturn 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

1.21 Common mistakes

1.22 Worked triage examples

ObservationClassificationFirst action
Quoted text reaches end of fileSyntaxErrorInspect the opening quote and surrounding line
List position equals list lengthIndexErrorReview the valid zero-based range
Impact is 14ValueErrorValidate the documented 0–10 range
HTTP capability is absentPermissionErrorConfirm necessity and host policy
Instruction budget is exhaustedResourceLimitErrorInvestigate loops and workload bounds
Registered provider throws unexpectedlyHostErrorUse the request ID to inspect trusted logs

1.23 Guided practice

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:

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

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.

← Previous Next →