Use error handlers for unexpected, exceptional conditions that need a fallback response, and use scenario settings for expected, configurable variations in normal operation. Error handlers catch failures and provide a graceful recovery path, while scenario settings let you define different behaviors for different, anticipated situations. This article explains the difference, when to choose each, and how they work together in real applications.
Background: Two Different Problems
Error handling and scenario configuration solve different problems, and confusing them leads to messy code. Error handling is about dealing with things that go wrong: a network request times out, a file is missing, a calculation produces an invalid result. Scenario settings are about choosing among valid, expected behaviors: a user selects a different currency, a system runs in a different environment, a feature has a different threshold for different customer tiers.
The key distinction is unexpectedness. Errors are by definition unexpected—you don't plan for them, but you must handle them. Scenarios are expected—you know they exist and you plan for them by making them configurable. Mixing these up often results in using exceptions for control flow (which is an anti-pattern) or using configuration flags to mask bugs (which hides problems).
How Error Handlers Work
Error handlers are code blocks that execute when an exception or error condition occurs. In most languages, you have a try-catch-finally structure, or you can register global handlers for uncaught exceptions. The purpose is to:
- Log the error with context (what failed, when, and the state)
- Return a meaningful fallback value or a user-friendly message
- Clean up resources (close files, release connections)
- Decide whether to retry or fail fast
For example, in a web application, an error handler might catch a database connection failure and return a cached response instead of a 500 error. In a desktop app, it might show a dialog with a "Report Issue" button.
Good error handlers are specific—they catch only the errors they know how to handle. A catch-all handler that swallows every exception is dangerous because it can hide serious bugs. The best practice is to have a generic handler as a last resort, but to also have specific handlers for known failure modes.
How Scenario Settings Work
Scenario settings are configuration options that alter how a system behaves under normal, expected conditions. They are typically stored in configuration files, environment variables, or a database, and they are read at runtime. Examples include:
- Feature flags (enable/disable a feature for a subset of users)
- Environment settings (development, staging, production)
- Business rules (tax rate, shipping threshold, discount percentage)
- User preferences (language, timezone, units of measurement)
Scenario settings are usually applied before a process starts or at decision points in the code. They are not triggered by failures; they are part of the normal decision-making flow. For instance, an e-commerce site might have a setting for "free shipping threshold"—if the cart total is above that threshold, shipping is free; otherwise, it is charged. That is a scenario setting, not an error handler.
The key is that scenario settings are expected and configurable. They can be changed without modifying code, often at runtime. This makes them powerful for A/B testing, gradual rollouts, and adapting to different markets.
Choosing Between Them: A Decision Framework
When you encounter a situation that could be handled either way, ask these questions:
- Is this an expected condition? If yes, it is a scenario. If no, it is an error.
- Can the system continue without a fallback? If not, you need an error handler. If yes, you might still want one, but it is not critical.
- Does the behavior need to change without code deployment? If yes, use scenario settings. If no, a simple conditional in code might suffice.
- Is the condition a failure of a dependency? (e.g., API down, file missing) Then it is an error, not a scenario.
- Is the condition a business rule? (e.g., different pricing for different regions) Then it is a scenario.
Consider a payment gateway. If the gateway returns "insufficient funds", that is an expected business outcome—it is a scenario. You should handle it as a normal response, maybe with a specific message. But if the gateway times out, that is an error—you need an error handler to retry or fail gracefully.
Common Problems and Pitfalls
One common mistake is using exceptions for scenario control. For example, throwing an exception when a user enters an invalid email format is wrong—that is an expected validation failure, not an error. It should be handled as a scenario (return a validation message) rather than as an exception. This is called "using exceptions for control flow" and it makes code harder to read and slower.
Another pitfall is making scenario settings too granular. If you have dozens of flags that each change behavior slightly, the system becomes hard to reason about. It is better to have a few well-defined scenarios than many overlapping flags.
Also, beware of error handlers that mask configuration errors. If a setting is invalid, that is an error, not a scenario. Your error handler should not silently fall back to a default value; it should log and alert so that the misconfiguration is fixed.
Comparison: Error Handlers vs Scenario Settings
| Aspect | Error Handlers | Scenario Settings |
|---|---|---|
| Trigger | Exception or failure | Normal condition |
| Expectation | Unexpected | Expected |
| Purpose | Recover, log, fallback | Configure behavior |
| Change frequency | Rarely (code changes) | Often (config changes) |
| Example | Database down | Tax rate for a country |
| Implementation | try-catch, global handlers | Config file, feature flags |
They are not mutually exclusive. In fact, they often work together. For example, a scenario setting might specify a timeout value, and an error handler catches the timeout exception and retries with a backoff. The setting determines the behavior, and the handler deals with the failure.
Costs and Trade-offs
Error handlers have a cost in complexity. Each try-catch block adds nesting and can obscure the main flow. Overusing them makes code hard to follow. They also have a performance cost when exceptions are thrown, as stack traces are expensive to generate.
Scenario settings have a cost in configuration management. You need to validate settings, document them, and ensure they are applied consistently across environments. Too many settings can lead to an unmanageable configuration matrix.
In practice, the cost of a misconfigured setting is usually lower than the cost of an unhandled error. An unhandled error can crash the system; a misconfigured setting usually just produces wrong behavior that is caught in testing. So, when in doubt, lean toward making something a scenario setting rather than an error, but always have a safety net handler for truly unexpected failures.
Frequently Asked Questions
Q: Can I use scenario settings to handle errors?
No. Scenario settings are for expected conditions. If you try to handle an unexpected failure with a setting, you are essentially saying "this failure is normal" and you will likely hide real problems. Use error handlers for failures, and scenario settings for expected variations.
Q: Should I use a global error handler or per-function handlers?
Both. Use per-function handlers for specific known failures (e.g., file not found) and a global handler as a last resort for anything uncaught. The global handler should log the error and show a friendly message, but it should not try to recover from unknown errors.
Q: How do feature flags relate to scenario settings?
Feature flags are a type of scenario setting. They allow you to turn features on or off for different users or environments without deploying code. They are a common implementation of scenario settings.
Q: What is the best way to log errors?
Log the error message, stack trace, timestamp, and any relevant context (user ID, request ID, input values). Use a structured format like JSON so that logs can be searched and analyzed. Avoid logging sensitive data like passwords or credit card numbers.
Q: How many scenario settings is too many?
There is no set number, but if you find yourself combining multiple settings to describe a single behavior, you probably have too many. Group related settings into a single configuration object or use a hierarchy. Aim for a small set of orthogonal settings that can be combined logically.
Q: Should I use exceptions for validation?
No. Validation failures are expected scenarios. Return a result object with error messages or use a validation framework. Exceptions should be reserved for unexpected conditions that you cannot handle locally.
Alternatives and Best Practices
Alternatives to error handlers include return codes, result objects, and the Either pattern from functional programming. These make errors explicit in the type system and force the caller to handle them. They are often cleaner than exceptions for expected failures.
Alternatives to scenario settings include code constants, inheritance, and strategy patterns. These are compile-time choices and are less flexible but simpler. Use them when the behavior does not need to change at runtime.
Best practice is to start with scenario settings for anything that is a business rule or user preference, and use error handlers for anything that is a system failure. Document your settings and your error handling policy. Test both: test that settings produce the expected behavior, and test that error handlers fire when dependencies fail.
In summary, the choice is not either/or—it is about using the right tool for the right situation. Error handlers protect you from the unexpected; scenario settings give you control over the expected. Use both, but use them appropriately.