Insufficient account balance and database connection interruptions are both wrapped in Error('operation failed'). The caller can only display the same message and cannot determine whether it is worth retrying. Wrapping an exception with Result does not automatically improve the design; the key is whether the failure classification supports taking action.
The error model should start with the decisions that the caller needs to make. Which failures are part of normal business operations, which ones need to be logged and alerted, and which results are currently unconfirmed. The more categories you have, the better. If you can’t form different types of handling, it’s usually just noise.
Business Rejection is an Expected Outcome
type ReserveResult =
| { ok: true; reservationId: string }
| { ok: false; reason: 'sold-out' }
| { ok: false; reason: 'invalid-quantity' };
“Out of stock” is a normal occurrence in the purchase process and does not necessarily indicate a system error. The caller should prompt the user to modify the quantity or choose a different item. The return value should retain sufficient business information, but should not directly pass database internal error messages to the user.
If the connection fails, it does not belong to this business integration, unless the interface explicitly models system failures as recoverable states. Either throwing an exception or returning an error result can be used, but it is important that the team agrees on a consistent approach and does not randomly mix them within the same module.
Unknown results cannot be disguised as failures.
After sending a request to the payment provider and experiencing a timeout, the payment may have already been successful. The message “Payment failed, please retry” is intended to encourage users to re-attempt the payment. The correct model might require a “pending” status and provide a mechanism for querying or coordinating the payment process in the background.
The “Unknown” state should carry a stable operation identifier, rather than just the network request number for this specific instance. This ensures that user retries, customer service investigations, and recovery tasks can all identify the same underlying business intent. Once the final state changes, the interface should clearly communicate the result.
This indicates that error types are often closely related to business states. Simply classifying network errors based on linguistic anomalies cannot determine how to recover a payment transaction. The adapter layer needs to translate the supplier’s semantics into results that are understandable within the domain.
The payment adapter knows that a request has been sent but not confirmed, and can return an identifier for the pending operation. The domain service persists the status and schedules a query. The interface provides a way to view the status, without immediately prompting for further payment. This type corresponds to a real recovery path and cannot simply add an “unknown” enumeration without anyone handling it. When the timeout expires and confirmation cannot be made, it triggers a manual exception process and preserves the evidence.
If the supplier supports idempotent keys, retries should use the same intent. If they support querying, reconciliation should be performed based on operation identifiers. However, if the supplier does not support either of these, the guarantee of automatic retries is limited, and it is necessary to acknowledge this. The type of network error itself cannot determine the payment result; the adapter layer combines the request stage with the supplier’s agreement conversion. Mapping all TimeoutError exceptions to failure will result in the loss of the most important information.
The successful outcome also differs from the current resource state. A successful response can re-process the same order identifier, and the order is subsequently cancelled without causing the initial creation to become a system error. The caller needs to use resource queries to obtain the current state, while historical operation results maintain a stable semantic meaning. The type name and field distinction differentiates these two facts, preventing the error layer from carrying the entire business lifecycle.
The Location of Capture Determines Information Loss
At the lowest level, all exceptions are converted to null. The upper layers will be unable to distinguish between non-existent and query failures. You can only capture known exceptions, such as unique constraint conflicts, and convert them into business results. Other exceptions are propagated upwards, retaining their original causes.
The owner and the error owner can be different. If the storage identification connection fails, the application layer decides whether to retry. The entry point determines how to handle user feedback. The return type carries an actionable category, preventing the lowest level from directly sending user notifications. Once the responsibility is clearly defined, the recovery logic will not be scattered across each capture branch.
User-visible messages and diagnostic information should be kept separate. The former should explain the actions that can be taken, while the latter should help engineers identify dependencies, operations, and error classifications. Error identifiers can be linked to both, but they should not expose tokens, query parameters, or internal paths.
Using Result for pure business functions makes it easier to exhaust all possible outcomes. Program defects or unrecoverable exceptions can be thrown, and the entry boundary safety record and transformation can be used. Another option is to use Result throughout the project, provided that system failures are not treated as normal rejections and ignored by the caller. Choose the approach that aligns with local conventions and avoids large-scale rewriting of all modules to introduce new containers. The key is to maintain consistency in semantics and processing responsibilities, without forcing every function to have the same return shape.
Unexpected increase in cause: This helps pinpoint the root failure. The log contains a boundary record, and other layers add necessary context. Avoid repeating the same error message in each layer, as this can make a single failure appear as multiple incidents. Also, do not simply return “undefined” after catching the error at the entry point. Unknown defects require visible errors, while business rejections require actionable prompts. Both should be securely masked. Record who owns the recovery, who owns the notification, and who owns the metrics, to reduce redundancy.
Error messages are presented using user actions, such as modifying quantity, re-verifying, or waiting for confirmation, rather than relying solely on internal error codes. The machine code is stable, and the error messages can be improved and translated. The English and simplified Chinese versions of the same business category do not require reverse logic based on language text. Long error descriptions on mobile devices can be scrolled through, and focus and status notifications allow assistive technologies to detect changes.
The service layer already has a retry budget, and the frontend should also avoid infinite polling every second. Once the result is confirmed, provide a reasonable query path and stop conditions. If the deadline is exceeded, indicate that the result is currently uncertain rather than automatically marking it as a failure. Closing the page does not cancel the accepted transaction, and subsequent logins can still query. The recovery process should transition from a type-based approach to a product-based state to avoid a situation where the container is visually appealing but users have no way to access it.
Finally, a brief review of all catch blocks:
- Are the correct categories known?
- Are unknown categories retained?
- Are logs logged consistently?
- Are secrets properly masked?
- Are retries idempotent?
This review complements exhaustive checking at compile time, helping to identify unexpected side effects. By reducing the number of error types, this approach provides more value than a standard Error when the corresponding action actually exists.
Exhaustive Handling of Future Change Protection
When using exhaustive search and adding a new reason, the compiler should be informed of the callers that need to be updated. The default branch simply displays “failed,” which may pass the compilation check but could mask new states that require different operations.
External interfaces may still send unknown error codes. The adapter layer should have a controlled fallback mechanism. This fallback is part of a runtime compatibility strategy, and it does not mean that all errors within the domain must be represented using an unlimited open string.
When versioning error types, it’s also important to consider the client. Adding new enum values can be a disruptive change, especially if it relies on strong assumptions about the client. Therefore, the external protocol can retain instructions for handling unknown code, while the internal model maintains a more explicit classification.
New code from vendors, driver errors, or incorrect network library changes can all exceed the scope of the enumerated errors. The adapter layer retains control over unknown failures, including non-sensitive reasons and associated IDs, while the internal model remains limited and actionable. “Unknown” does not necessarily mean “retryable,” and it does not execute three attempts if there is no matching business rejection. Default security failures complement explicit recovery rules.
Thoroughly check the internal branches of the protection mechanism, while external protocols require forward compatibility. The two layers can be different, without forcing all consumers to accept the same strict union. Stable code returned by the API and user-actionable instructions, along with improved error messages in natural language. The frontend does not parse Chinese sentences to determine their type. The internal cause-and-effect chain of server-side exceptions is preserved, and public responses do not expose stack traces, queries, or keys.
Whether an error is logged depends on the responsibility. Normal, successful operations can be tracked using business metrics, while database errors are logged once at the entry point. Additional layers add context without repeating the error message. Each time an error is caught, it indicates why the error occurred, and if it cannot be determined, the error is propagated. Returning a null value for an error may seem like a simplified approach, but in reality, it places the burden of guessing on the caller.
Avoid scattering retry strategies within catch blocks
Retries should only be attempted when the operation is clearly retryable, idempotent, and sufficient budget is available. Multiple loops within individual functions can easily lead to request amplification, so it should be configured centrally, knowing the boundaries of the dependencies, and inform the upper layers whether a recovery attempt has been made.
Incorrect results can include retry suggestions, but these should not be treated as mandatory commands. The caller may not have sufficient time, or the user may have already cancelled. Permanent business rejections should not use the same fallback strategy.
For batch operations, individual success/failure needs to be reported separately. Returning a single overall success/failure will lose information about individual successful/failed items. Each result should have a clear relationship with the overall status, and compensation or retries should only be applied to the specific items that require attention.
Achieving Success Requires a Stable Project Identity
Export ten objects in bulk: seven successful, three failed. The result includes a stable ID and status for each item, and the overall status indicates partial completion. Retries are only applied to failed items that can be retried. Successful items do not trigger side effects again. The position in the list is not a business identifier, and you cannot select a retry item based on the index after sorting. Unidentified items have a separate confirmation process and cannot be executed blindly along with a clear failure.
The business results can be saved to a persistent task state, and can still be viewed after the front-end refresh. A single HTTP total error cannot erase the fact that a submission has been successful, and compensation cannot assume that all actions can be undone. The error model works in conjunction with the task protocol to inform the user what has been completed, what has not yet been confirmed, and what the next action should be. The container structure only provides storage; it does not guarantee these things itself.
The retry suggestions include specific conditions and a limited time frame. The caller should still check the budget, cancel, and ensure idempotency. Do not treat boolean retryability as a universal condition for executing commands across all layers. If the adapter layer has already attempted a retry, it should inform the upper layer about the failed attempt to avoid redundant operations. The error budget and number of calls can be aggregated for observation, and sensitive operations should not be treated as unlimited metrics.
Reversing Error Classification from Recovery Actions
To address insufficient stock, the system prompts the user to change the quantity. To handle expired login credentials, the system requires re-authentication. If the database connection is lost, the controlled action fails, and the administrator is notified. If the payment result is unknown, the system continues to query the same intent. These four actions are initially established, and then their types are defined. If two categories always map to the same actions and diagnostic responsibilities, they can be merged. If one category mixes retry and prohibits retry, further decomposition is required. The granularity of the categories is determined by the decision-making requirements, not by the number of exception classes.
The machine code should remain stable, but it is not necessary to preserve all errors in the internal dependencies. Upgrading the database driver may change class names and messages, while the storage adapter identifies supported categories. The application layer should maintain a stable meaning. Identifying unique constraint conflicts also requires knowing the specific constraints: duplicate email addresses may indicate business rejection, conflicts in unique keys for internal events may indicate idempotent re-execution, and unknown constraint conflicts may indicate program defects. Treating all occurrences of a generic error code as user re-entry will obscure different facts.
The following information is required for the owner to regain control:
- The adapter needs to know the vendor’s protocol.
- The application service needs to know the overall duration.
- The entry point needs to know the user feedback mechanism.
The adapter can provide limited retry suggestions, the application layer can determine if there is a budget, and the entry point only converts public responses. This prevents both the entry point and the adapter from retrying independently, and also prevents the wrong object from directly calling the notification service. The data type is passed, the strategy module makes the decision, and the side effects have a clear execution point.
Preserving Existing Facts When Combining Multiple Operations
The order creation process succeeded, but sending the notification failed. This process cannot simply return “create-order-failed.” The order already exists, and re-creation by the user may result in duplication. The result can indicate that the order was created successfully but the notification is pending, or that the notification should be treated as a reliable background task. The specific choice depends on the product contract. The error container cannot automatically roll back submitted side effects; the caller must know which facts have been established.
This issue also occurs with bulk requests. With three submissions, one succeeds, one is explicitly rejected, and one results in an unknown outcome. The overall failure rate mixes the results of all three actions together. Each submission uses a stable business identity. Successful submissions are no longer executed, rejected submissions allow users to modify them, and unknown submissions trigger a confirmation query. The overall partial state is convenient for displaying information, but it cannot replace the actual project results. Changes in the order of the submissions should not affect the recovery object.
The compensation process may also fail or be impossible. After a successful deduction, canceling the reserved inventory does not automatically mean the deduction disappears. Refund is another state-based operation. The error handling model should express both the need for compensation and the need for confirmation, while persistently saving recovery records, rather than simply returning the original failure after a single refund call within a catch block. Complex processes should use existing reliable task or state machine mechanisms, rather than relying on nested Result objects to simulate transactions.
Handling External Unknowns and Internal Omissions Differently
The new “payment-review” feature introduces a potential issue: internal callers might miss branch updates, leading to incomplete checks and potentially exposing compilation errors. Additionally, if a vendor introduces code that only becomes visible during server runtime, it requires controlled fallback and alerting. Both of these scenarios should not rely on a default “failed” return, as this could mask internal omissions and also lead to external uncertainties being misinterpreted as failures.
The final result retains non-sensitive association identifiers and diagnostic categories, while the public response only provides actionable steps. Do not treat the vendor’s original message as user instructions, as the message may contain internal paths, account information, or even be affected by user input. User-visible text can be internationalized, and the client acts based on machine code, without parsing Chinese or English error sentences.
The evolution of the protocol requires checking compatibility with older consumers. New error codes can be displayed by older clients to indicate a generic controlled state, but cannot automatically enable retries. The documentation explicitly states that unknown codes should be treated conservatively, and clients have limited polling and refresh strategies. The server can maintain strict compatibility, with the boundary layer responsible for ensuring compatibility, thus preserving static checks while acknowledging that deployed clients will not automatically upgrade with the code.
Log and Error Traceability Doesn’t Necessarily Need to Be Public
The diagnostic objects can include dependency, operation, attempt, and cause. The user results only contain stable error categories and query identifiers. These two structures are constructed separately to reduce the risk of serializing the complete error sequence. The “cause” chain is used by maintainers to find the original failure, but it does not mean that each layer should be printed once. One entry record contains the complete diagnosis, and other layers provide necessary context and continue to propagate.
Normal business rejections can be counted, but they should not trigger a system-wide incident. At the same time, a sudden increase in rejections could be a sign of a product issue or an attack, which can be identified through independent business monitoring. System failures should not be converted into “sold-out” to reduce alerts, and unknown results should not be treated as successes to increase success rates. Incorrect categorization affects both recovery and statistics; categories must have accurate semantic meaning.
The correlation identifiers in the logs are used for security investigations and are not intended as high-volume tag indicators. Complete requests, payment credentials, and private payloads do not enter the generic error object; otherwise, any output object at any level could leak. Testing can verify the public response keys and log filtering to ensure that sensitive data does not leak through exceptions, nested fields, or serialization bypasses.
Using Mutation Testing to Verify Caller Decision-Making
The deliberate changes were made to:
- Change “sold out” results to indicate a system failure, which should reveal error messages or warnings;
- Change “pending confirmation” to indicate a clear failure, which should trigger a client error and request re-payment;
- Change “unknown external code” to indicate retryable, which should reveal that the budget or recovery strategy does not comply with the contract.
These changes demonstrate that the tests cover the intended behavior, rather than simply checking for the presence of an “OK” field.
Finally, the recovery process can continue across reboots. After refreshing the page, the same intent can still be queried. Task records are saved in categorized versions, and old tasks can be interpreted by a compatible adapter. If an error occurs only once in an HTTP response, the process loses its execution responsibility after completion. Type design and persistence state, along with user actions, are validated to truly reduce the guesswork of the caller.
If the team adopts a unified Result library, first confirm that it preserves causal chains, supports asynchronous composition, and provides a way to express partial success. The library provides container operations but does not dictate the semantics of errors. Test with existing call points; only promote after reducing real-world repetition judgments. This avoids introducing new syntax and still guessing whether to retry in each branch.
Actions to Test Error Paths
Verifying a sold-out item will not trigger a system alert. Database disconnection will not be displayed as “item not found.” Payment timeout will go to “pending confirmation” instead of immediately re-paying. The only complete diagnostic check is performed once, and user responses do not contain sensitive information.
Each catch can be inspected: Does it know what failures it has encountered? Does it modify the semantics? Does it retain the necessary information for recovery? This is more valuable than requiring all functions to return a generic container.
A good error model reduces the guesswork for the caller. The type is simply a carrier; the real design focus is on how the system and the user will continue to function after a failure occurs.
In testing, check both type and action simultaneously:
- “Out of Stock” prompt: Modify quantity
- Authentication failure: Initiate re-validation
- Unknown payment: Proceed to confirmation
- System failure: Log once and safely fail.
Intentionally add new domain reasons:
- Compilation should indicate that the caller is not handled.
- Intentionally add new external code: Runtime adaptation should be controlled and fallback.
Two types of unknowns are different and cannot be hidden by a single “default”. The design’s goal is for the caller to continue accurately, not to put all exceptions into a single generic.