Error Handling Patterns
Result Patterns
Represent success or failure with data.
Result Patterns
result_pattern.js
const raw = "15";
const number = Number(raw);
let ok = true;
let value = 0;
let reason = "";
if (Number.isNaN(number)) {
ok = false;
reason = "not a number";
} else if (number < 0) {
ok = false;
reason = "negative";
} else {
value = number;
}
const label = ok ? "value:" + value : "error:" + reason;
console.log("raw=" + raw);
console.log("label=" + label);
result-pattern
Some code avoids throwing and returns a result shape instead. This keeps the success path and failure reason explicit.