Demonstrates improved unwrap() diagnostics with automatic source location.
Demonstrates improved unwrap() diagnostics with automatic source location.Shows how unwrap() on Result<T> and Optional<T> captures the call site via std::source_location, producing detailed error messages that include file name, line number, and function context. Also demonstrates safe alternatives: unwrap_or, is_ok/is_err checks, and monadic operations.
- See also
- kcenon::common::Result
-
kcenon::common::Optional
#include <iostream>
#include <string>
if (denominator == 0) {
return make_error<int>(
-1,
"Division by zero",
"math_module",
"Cannot divide by zero"
);
}
return ok(numerator / denominator);
}
if (id == 42) {
}
}
std::cout << "=== Improved unwrap() Error Messages Demo ===\n\n";
std::cout << "1. Result<T>::unwrap() with error:\n";
std::cout << "-----------------------------------\n";
try {
int value = result.unwrap();
std::cout << "Value: " << value << "\n";
} catch (const std::exception& e) {
std::cout << "Exception caught:\n" << e.what() << "\n\n";
}
std::cout << "2. Optional<T>::unwrap() with None:\n";
std::cout << "------------------------------------\n";
try {
std::string name = user.unwrap();
std::cout << "User: " << name << "\n";
} catch (const std::exception& e) {
std::cout << "Exception caught:\n" << e.what() << "\n\n";
}
std::cout << "3. Safe alternatives to unwrap():\n";
std::cout << "----------------------------------\n";
int value1 = result.unwrap_or(0);
std::cout << "unwrap_or(0): " << value1 << "\n";
if (result.is_ok()) {
std::cout << "Value: " << result.value() << "\n";
} else {
auto error = result.error();
std::cout <<
"Error: " <<
error.message <<
"\n";
std::cout <<
" Code: " <<
error.code <<
"\n";
std::cout <<
" Module: " <<
error.module <<
"\n";
}
if (result.is_ok()) {
std::cout << "Value via is_ok check: " << result.value() << "\n";
} else {
std::cout << "Result is in error state\n";
}
.map([](int x) { return x * 2; })
.unwrap_or(-1);
std::cout << "Monadic map result: " << doubled << "\n";
std::cout << "\n=== Demo Complete ===\n";
}
return 0;
}
Optional type similar to std::optional with Rust-like API.
Result type for error handling with member function support.
Umbrella header for Result<T> type and related utilities.
Result< int > divide(int a, int b)
Optional< std::string > find_user(int id)
void demonstrate_improved_error_messages()