Common System 0.2.0
Common interfaces and patterns for system integration
Loading...
Searching...
No Matches
result_example.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
17
19#include <iostream>
20#include <fstream>
21#include <string>
22
23using namespace kcenon::common;
24
25// Example function that can fail
26Result<int> divide(int a, int b) {
27 if (b == 0) {
28 return make_error<int>(
30 "Division by zero",
31 "math_module"
32 );
33 }
34 return ok(a / b);
35}
36
37// Example function that reads a file
38Result<std::string> read_file(const std::string& path) {
39 if (path.empty()) {
42 "Path cannot be empty",
43 "file_module"
44 );
45 }
46
47 std::ifstream file(path);
48 if (!file.is_open()) {
51 "File not found: " + path,
52 "file_module"
53 );
54 }
55
56 std::string content((std::istreambuf_iterator<char>(file)),
57 std::istreambuf_iterator<char>());
58 return ok(content);
59}
60
61// Example of chaining operations
62Result<int> parse_and_compute(const std::string& expr) {
63 // Simple parser for "a/b" format
64 auto pos = expr.find('/');
65 if (pos == std::string::npos) {
66 return make_error<int>(
68 "Invalid expression format",
69 "parser"
70 );
71 }
72
73 try {
74 int a = std::stoi(expr.substr(0, pos));
75 int b = std::stoi(expr.substr(pos + 1));
76 return divide(a, b);
77 } catch (const std::exception& e) {
78 return make_error<int>(
80 std::string("Parse error: ") + e.what(),
81 "parser"
82 );
83 }
84}
85
86int main() {
87 std::cout << "=== Result Pattern Examples ===\n\n";
88
89 // Example 1: Basic usage with member methods
90 std::cout << "1. Basic division:\n";
91 auto result1 = divide(10, 2);
92 if (result1.is_ok()) {
93 std::cout << " 10 / 2 = " << result1.value() << "\n";
94 }
95
96 auto result2 = divide(10, 0);
97 if (result2.is_err()) {
98 const auto& err = result2.error();
99 std::cout << " Error: " << err.message
100 << " (code: " << err.code << ")\n";
101 }
102
103 // Example 2: Using value_or / unwrap_or
104 std::cout << "\n2. Using value_or:\n";
105 auto value = divide(10, 0).unwrap_or(-1);
106 std::cout << " 10 / 0 with default -1 = " << value << "\n";
107
108 // Example 3: Pattern matching with if-else
109 std::cout << "\n3. Pattern matching:\n";
110 auto result3 = parse_and_compute("20/4");
111 if (result3.is_ok()) {
112 std::cout << " Success: " << result3.unwrap() << "\n";
113 } else {
114 std::cout << " Failed: " << result3.error().message << "\n";
115 }
116
117 // Example 4: Monadic operations using member methods
118 std::cout << "\n4. Monadic operations:\n";
119 auto result4 = divide(100, 5);
120 auto doubled = result4.map([](int x) { return x * 2; });
121 if (doubled.is_ok()) {
122 std::cout << " (100 / 5) * 2 = " << doubled.value() << "\n";
123 }
124
125 // Example 5: Chaining with and_then using member methods
126 std::cout << "\n5. Chaining operations:\n";
127 auto chain_result = divide(50, 5)
128 .and_then([](int x) { return divide(x, 2); });
129 if (chain_result.is_ok()) {
130 std::cout << " (50 / 5) / 2 = " << chain_result.value() << "\n";
131 }
132
133 // Example 6: Error recovery with or_else using member methods
134 std::cout << "\n6. Error recovery:\n";
135 auto recovered = divide(10, 0)
136 .or_else([](const error_info&) { return ok(0); });
137 std::cout << " 10 / 0 with recovery = " << recovered.value() << "\n";
138
139 // Example 7: try_catch wrapper
140 std::cout << "\n7. Exception wrapping:\n";
141 auto wrapped = try_catch<int>([]{
142 throw std::runtime_error("Something went wrong");
143 return 42;
144 }, "example_module");
145
146 if (wrapped.is_err()) {
147 const auto& err = wrapped.error();
148 std::cout << " Caught exception: " << err.message << "\n";
149 }
150
151 std::cout << "\n=== Examples completed ===\n";
152 return 0;
153}
Result type for error handling with member function support.
Definition core.cppm:165
const error_info & error() const
Get error reference.
Definition core.h:405
constexpr int NOT_FOUND
Definition compat.h:32
constexpr int INVALID_ARGUMENT
Definition compat.h:31
Core interfaces.
Definition adapter.h:21
Result< T > make_error(int code, const std::string &message, const std::string &module="")
Create an error result with code and message.
Definition utilities.h:91
Result< T > try_catch(F &&func, const std::string &module="")
Convert exception to Result with automatic error code mapping.
Definition utilities.h:173
VoidResult err(const error_info &error)
Factory function to create error VoidResult.
Definition core.cppm:432
VoidResult ok()
Create a successful void result.
Definition utilities.h:71
Umbrella header for Result<T> type and related utilities.
Result< int > parse_and_compute(const std::string &expr)
Result< std::string > read_file(const std::string &path)
Result< int > divide(int a, int b)
int main()
Standard error information used by Result<T>.
Definition core.cppm:106