Software EngineeringArchive edition6 min read

Handling errors in a predictable way

Make failures understandable to the caller and observable to maintenance teams.

Interlocking modular blocks and structured outlines — Handling errors in a predictable way
Original ARTware computational illustration.

A website visitor submits a request and sees the words 'Something went wrong.' This could mean that a required field is missing, that a remote data source is temporarily unavailable or that a programming error occurred. The visitor cannot determine what to do next. A developer examining the application's records later encounters the same generic message. Without additional evidence, recovering from the failure is difficult. The problem is not merely the wording of the message. The system has collapsed several meaningful outcomes into one undifferentiated state.

Classify errors according to what can happen next

A useful error design describes outcomes in terms of the operation being attempted and the available recovery path. The simplest distinction is between invalid input and unavailable execution. If a quantity must be positive and the submitted quantity is zero, the caller can correct it and submit a valid request. Repeating exactly the same request will not help. If the information source is unavailable, changing a perfectly valid quantity might not help either. The caller may be able to try again later, once the dependency returns.

Unexpected internal failures form another category. A missing configuration value or an unanticipated runtime exception may require attention from a maintainer. The caller cannot be expected to diagnose it from a technical report. The appropriate visible behavior is to explain that the operation could not be completed and, where useful, provide an opaque reference that allows support or maintenance teams to find the corresponding event. This separates the information required by the visitor from the diagnostic information needed to investigate the implementation.

Create a small error vocabulary

An application interface benefits from a documented set of error outcomes. Use a stable code or equivalent machine-readable condition for each category that callers genuinely need to distinguish. A response for incomplete input can identify the affected field and indicate the correction required. A response for temporarily unavailable processing can carry an outcome that a calling application recognizes as temporary. An ordinary presentation can display friendly text, while a program can react based on the stable condition rather than parsing the exact words used in that text.

Resist creating an error code for every line of implementation. If several internal failures have the same consequences for the caller, they may share one external result even though diagnostic records distinguish them. Conversely, one implementation exception might represent several different caller-visible situations depending on where it occurred. Define the public vocabulary starting with the consumer's decisions. A stable agreement makes it possible to improve the internal implementation and rewrite visible messages without accidentally breaking applications that depend on the outcome.

Match interface responses to actual outcomes

Related reading: Designing modules around stable boundaries.

For a web endpoint, the response status, response body and operation result should describe a coherent outcome. An invalid request should receive a response indicating that the request could not be accepted due to its content. A request that fails after reaching an unavailable dependency should be distinguishable from a successfully completed one. Avoid placing the words 'failed to save' in a body whose status and structure otherwise make it appear to be an ordinary confirmation. Machine consumers may not read the explanatory sentence.

A missing record provides an instructive distinction. If a public catalog lookup confirms that no eligible match exists, the result can indicate absence. If the lookup cannot reach its source at all, it has no basis for claiming that the item does not exist. Returning an empty result in both cases simplifies the calling code but turns uncertainty into an apparent fact. The visitor might incorrectly conclude that the listing was removed. Make the dependency failure visible as a failure or use a deliberately designed fallback whose limitations are clearly communicated.

Be precise about the state left behind

An error message is only half the story when an operation changes stored data. Suppose an application creates a report record, generates a file and marks the report as ready. If generation fails after the record has been created, what will the report page show? Is the record recoverable? Should another submission create a separate record or continue the previous operation? Define the state transitions so the user does not receive a failure message while the stored report claims to be complete. This design often requires treating related changes as one logical operation.

Interlocking modular blocks and structured outlines
ARTware visual study. A complementary computational composition.

For several updates to one database, a transaction may make it possible to commit the complete change or leave the previous state intact. For a workflow that spans a database, file output and another service, the application may instead represent intermediate states explicitly. A report can remain pending until a durable file is available and only then move to ready. If generation stops, it can enter a failed state with a well-defined recovery or resubmission path. The important point is to align the visible outcome with the actual recorded state.

Write messages that help the intended reader

Compare two validation messages for the same missing field: 'Invalid request' and 'Enter a title before saving this record.' The second identifies both the problem and the action the user can take. A temporary failure message may say that the requested data could not be loaded and indicate that the previous saved content remains unchanged, provided that claim is true. For an unexpected failure, distinguish what is known from what is uncertain. Avoid telling someone that a retry is safe if the system cannot determine whether the previous attempt created a record.

Operational records can contain more context than the visible message, but they still need to respect information boundaries. Record an operation identifier, a short failure classification and the stage where processing stopped. Depending on the setting, a stack trace or restricted diagnostic detail may be useful to maintainers. Do not place internal configuration, credentials or raw private input in a public response. Even internal logging should be limited to information that has a legitimate diagnostic purpose. Capturing every input by default is rarely necessary to identify the failed stage.

Catch failures at the level that can deal with them

A low-level function often cannot decide how the application should recover from a dependency failure. It may know that a requested operation did not complete, but not whether the calling workflow can fall back to existing data or must stop entirely. Let the failure reach the component that owns the relevant recovery policy. Catch known exceptions where corrective action or a meaningful mapping is possible. A top-level boundary can provide a consistent result for genuinely unexpected exceptions, preventing them from turning into apparently successful responses or leaking technical details.

Be cautious of a broad catch block that simply continues with a default value. Such code can create a new kind of failure several steps later, when other components rely on a value that was never obtained. If a default is a legitimate product decision, document the exact circumstances in which it is used and distinguish it from confirmed data. If the missing result is essential, stop the affected operation rather than inventing an answer. This makes the system more understandable both to the caller and to developers investigating a later inconsistency.

Test interruption as well as incorrect input

Prepare a small scenario for each meaningful error class. Call the operation with a missing required value and verify that it rejects the request without changing stored state. Supply valid input while the test environment deliberately makes a required dependency unavailable. Verify the returned condition and any recorded intermediate state. Introduce an unexpected failure in a controlled test setting and inspect what the caller receives. The response should be useful, but not disclose private implementation information. Confirm that a maintainer can associate it with a suitably limited diagnostic record.

Finally, exercise the documented recovery path. If a failed report can be retried, make the dependency available again and retry it. Verify that the result becomes ready once and that the earlier state no longer suggests the report failed. If an ordinary lookup can distinguish absent content from failed retrieval, test both routes separately. These examples turn general error-handling intentions into observable behavior. A future maintainer can improve the implementation while knowing that users and callers continue to receive outcomes on which their subsequent decisions can safely depend.

Explore the implementation area: Backend development.