### Rust Example: Using anyhow Context for Error Handling Source: https://docs.rs/anyhow/latest/anyhow/trait An example showcasing the usage of `context` and `with_context` methods from the anyhow crate to add descriptive context to errors during file operations. It demonstrates how context chains are printed and how to handle errors with context. ```Rust use anyhow::{Context, Result}; use std::fs; use std::path::PathBuf; pub struct ImportantThing { path: PathBuf, } impl ImportantThing { pub fn detach(&mut self) -> Result<()> {...} } pub fn do_it(mut it: ImportantThing) -> Result> { it.detach().context("Failed to detach the important thing")?; let path = &it.path; let content = fs::read(path) .with_context(|| format!("Failed to read instrs from {}", path.display()))?; Ok(content) } ``` -------------------------------- ### Rust Example Usage of ensure Macro Source: https://docs.rs/anyhow/latest/anyhow/macro Demonstrates the basic usage of the 'ensure' macro in Rust with a simple condition and a literal error message. ```Rust ensure!(user == 0, "only user 0 is allowed"); ``` -------------------------------- ### Rust Result Product Example Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates how to use the `product` method on an iterator of `Result` values. If any element in the iterator is an `Err`, the operation short-circuits and returns that `Err`. Otherwise, it returns the product of all `Ok` values. ```Rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Rust Result iter_mut Example Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates mutable iteration over the contents of a Result, modifying the Ok value if present. ```Rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Rust Result Sum Example Source: https://docs.rs/anyhow/latest/anyhow/type Illustrates the `sum` method for iterators of `Result` values. Similar to `product`, if an `Err` is encountered, it's returned immediately. Otherwise, the sum of all `Ok` values is computed and returned. ```Rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Custom Error Rendering Source: https://docs.rs/anyhow/latest/anyhow/struct Provides an example of how to manually render an error and its cause chain using `anyhow::Context` and iterating through the error chain. ```Rust use anyhow::{Context, Result}; fn main() { if let Err(err) = try_main() { eprintln!("ERROR: {}", err); err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause)); std::process::exit(1); } } fn try_main() -> Result<()> { ... } ``` -------------------------------- ### Main Function with anyhow::Result for Error Handling Source: https://docs.rs/anyhow/latest/anyhow/type An example of a `main` function that returns `anyhow::Result<()>`. This pattern allows for convenient error propagation using the `?` operator for operations that return `Result`, such as file reading and JSON parsing. Failures are automatically printed with context and a backtrace if captured. ```Rust use anyhow::Result; fn main() -> Result<()> { let config = std::fs::read_to_string("cluster.json")?; let map: ClusterMap = serde_json::from_str(&config)?; println!("cluster info: {:#?}", map); Ok(()) } ``` -------------------------------- ### Rust Result unwrap Method Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates the `unwrap` method to get the Ok value from a Result. This method panics if the Result is an Err, and its use is generally discouraged in favor of explicit error handling. ```Rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```Rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Rust Example: Downcasting with anyhow Context Source: https://docs.rs/anyhow/latest/anyhow/trait Illustrates how to use anyhow's context feature while maintaining the ability to downcast errors. It shows two scenarios: attaching insignificant context to downcastable errors and attaching downcastable context to insignificant errors. ```Rust use anyhow::{Context, Result}; fn do_it() -> Result<()> { helper().context("Failed to complete the work")?; ... } fn main() { let err = do_it().unwrap_err(); if let Some(e) = err.downcast_ref::() { // If helper() returned SuspiciousError, this downcast will // correctly succeed even with the context in between. } } ``` ```Rust use anyhow::{Context, Result}; fn do_it() -> Result<()> { helper().context(HelperFailed)?; ... } fn main() { let err = do_it().unwrap_err(); if let Some(e) = err.downcast_ref::() { // If helper failed, this downcast will succeed because // HelperFailed is the context that has been attached to // that error. } } ``` -------------------------------- ### Rust Example Usage of ensure with Custom Error Source: https://docs.rs/anyhow/latest/anyhow/macro Shows how to use the 'ensure' macro in Rust with a custom error enum, returning an instance of the enum if the condition fails. ```Rust #[derive(Error, Debug)] enum ScienceError { #[error("recursion limit exceeded")] RecursionLimitExceeded, ... } ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded); ``` -------------------------------- ### Example Usage of anyhow::Result Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates how to use the `anyhow::Result` type alias in function signatures. It shows two common patterns: `Result` which defaults to `anyhow::Error`, and `Result` for functions that might return a different specific error type. ```Rust use anyhow::Result; fn demo1() -> Result {...} // ^ equivalent to std::result::Result fn demo2() -> Result {...} // ^ equivalent to std::result::Result ``` -------------------------------- ### Rust: Get Value or Default with `unwrap_or` Source: https://docs.rs/anyhow/latest/anyhow/type The `unwrap_or` function returns the contained `Ok` value or a provided default if the `Result` is `Err`. Arguments are eagerly evaluated. ```Rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Rust Type Inference Error with anyhow::Result::Ok Source: https://docs.rs/anyhow/latest/anyhow/fn Illustrates a common type inference error (`E0282`) that can occur when using `anyhow::Result::Ok` without explicit type annotations. The example shows how the compiler cannot infer the error type `E` for `std::result::Result`. ```Rust error[E0282]: type annotations needed for `std::result::Result` --> src/main.rs:11:13 | 11 | let _ = anyhow::Result::Ok(1); | - ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result` | | | consider giving this pattern the explicit type `std::result::Result`, where the type parameter `E` is specified ``` -------------------------------- ### Using the anyhow Macro in Rust Source: https://docs.rs/anyhow/latest/anyhow/all Demonstrates the usage of the 'anyhow' macro for creating errors in Rust. This macro is part of the anyhow crate and simplifies error handling by providing context. ```Rust use anyhow::anyhow; fn main() { let err = anyhow!("Something went wrong"); println!("{}", err); } ``` -------------------------------- ### Rust: Get Type ID Source: https://docs.rs/anyhow/latest/anyhow/struct Retrieves the `TypeId` of the current type. This is part of the `Any` trait and is used for runtime type identification, often in conjunction with downcasting. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust Result expect Method Source: https://docs.rs/anyhow/latest/anyhow/type Shows how to use the `expect` method to retrieve the Ok value from a Result, panicking with a custom message if it's an Err. It's recommended to use pattern matching instead. ```Rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```Rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Rust Ok Function for anyhow::Result Source: https://docs.rs/anyhow/latest/anyhow/fn Demonstrates the usage of the `anyhow::Result::Ok` function, which simplifies the creation of `anyhow::Result` instances. It's particularly useful when type inference might otherwise fail to deduce the error type. ```Rust pub fn Ok(value: T) -> Result ``` -------------------------------- ### Rust Trait Context Implementation Source: https://docs.rs/anyhow/latest/anyhow/trait Demonstrates the `Context` trait in Rust's anyhow crate, which provides methods to wrap errors with additional context. It includes the `context` and `with_context` methods. ```Rust pub trait Context: Sealed { // Required methods fn context(self, context: C) -> Result where C: Display + Send + Sync + 'static; with_context(self, f: F) -> Result where C: Display + Send + Sync + 'static, F: FnOnce() -> C; } ``` -------------------------------- ### Get Underlying IO Error Kind Source: https://docs.rs/anyhow/latest/anyhow/struct Iterates through the error chain to find the first underlying io::Error and returns its kind. This is useful for specific error handling based on IO operations. ```Rust use anyhow::Error; use std::io; pub fn underlying_io_error_kind(error: &Error) -> Option { for cause in error.chain() { if let Some(io_error) = cause.downcast_ref::() { return Some(io_error.kind()); } } None } ``` -------------------------------- ### Rust: No-std Configuration for anyhow Source: https://docs.rs/anyhow/latest/anyhow/index Illustrates how to configure the `anyhow` crate for `no_std` environments by disabling the default "std" feature in `Cargo.toml` and mentions the requirement for a global allocator. ```toml [dependencies] anyhow = { version = "1.0", default-features = false } ``` -------------------------------- ### Result::transpose Method for Option Source: https://docs.rs/anyhow/latest/anyhow/type Explains the `transpose` method for `Result, E>`, which converts a `Result` containing an `Option` into an `Option` containing a `Result`. `Ok(None)` becomes `None`, while `Ok(Some(v))` and `Err(e)` become `Some(Ok(v))` and `Some(Err(e))` respectively. ```Rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Using the bail Macro in Rust Source: https://docs.rs/anyhow/latest/anyhow/all Illustrates how to use the 'bail' macro to return an error immediately from a function in Rust. This is useful for early exit conditions. ```Rust use anyhow::bail; fn might_fail(condition: bool) -> anyhow::Result<()> { if !condition { bail!("Operation failed due to condition"); } Ok(()) } ``` -------------------------------- ### Rust Result into_ok Method Source: https://docs.rs/anyhow/latest/anyhow/type Introduces the nightly-only `into_ok` method, which safely returns the Ok value from a Result without panicking. It's a compile-time safeguard against Results that can never be Err. ```Rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Rust: Construct Result from Residual Source: https://docs.rs/anyhow/latest/anyhow/type Provides experimental nightly-only APIs to construct a Result from compatible Residual types, specifically `Result` and `Yeet`. ```Rust impl where F: From, { fn from_residual(residual: Result) -> Result; } impl where F: From, { fn from_residual(_: Yeet) -> Result; } ``` -------------------------------- ### Using the ensure Macro in Rust Source: https://docs.rs/anyhow/latest/anyhow/all Shows the usage of the 'ensure' macro to check a condition and return an error if it's not met in Rust. This is commonly used for input validation. ```Rust use anyhow::ensure; fn process_data(value: i32) -> anyhow::Result<()> { ensure!(value > 0, "Value must be positive, got {}", value); // Process the data Ok(()) } ``` -------------------------------- ### Using anyhow::Result in Rust Source: https://docs.rs/anyhow/latest/anyhow/all Demonstrates the use of the 'Result' type alias provided by the anyhow crate for simplified error handling in Rust. It combines the standard Result with anyhow's error capabilities. ```Rust use anyhow::Result; fn read_config() -> Result { // Simulate reading a config file Ok("config_data".to_string()) } fn main() { match read_config() { Ok(config) => println!("Config: {}", config), Err(e) => eprintln!("Error reading config: {}", e), } } ``` -------------------------------- ### Rust: Create Errors with anyhow! Macro Source: https://docs.rs/anyhow/latest/anyhow/index Shows the usage of the `anyhow!` macro to create ad-hoc error messages with string interpolation, which are then returned as `anyhow::Error`. ```Rust return Err(anyhow!("Missing attribute: {}", missing)); ``` -------------------------------- ### Rust Result as_ref Source: https://docs.rs/anyhow/latest/anyhow/type Converts a reference to a Result<&T, &E> into a Result<&T, &E>. It produces a new Result containing a reference into the original, leaving the original untouched. ```Rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Rust: Early Return with bail! Macro Source: https://docs.rs/anyhow/latest/anyhow/index Provides a shorthand using the `bail!` macro for early return of an `anyhow::Error`, simplifying the code when an error condition is met. ```Rust bail!("Missing attribute: {}", missing); ``` -------------------------------- ### Rust: Debug format for Result Source: https://docs.rs/anyhow/latest/anyhow/type Implements the Debug trait for Result, enabling formatted output for debugging purposes if both the Ok and Err types implement Debug. ```Rust impl where T: Debug, E: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>; } ``` -------------------------------- ### Rust Result ok Source: https://docs.rs/anyhow/latest/anyhow/type Converts a Result into an Option, consuming the Result and discarding the error if present. ```Rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Rust: Add Context to Errors with anyhow::Context Source: https://docs.rs/anyhow/latest/anyhow/index Shows how to add contextual information to errors using the `context()` and `with_context()` methods from `anyhow`. This helps in debugging by providing higher-level details about where an error occurred. ```Rust use anyhow::{Context, Result}; fn main() -> Result<()> { ... it.detach().context("Failed to detach the important thing")?; let content = std::fs::read(path) .with_context(|| format!("Failed to read instrs from {}", path))?; ... } ``` -------------------------------- ### Rust: Propagate Errors with anyhow::Result and ? Source: https://docs.rs/anyhow/latest/anyhow/index Demonstrates using `anyhow::Result` and the `?` operator for concise error propagation in Rust. Any error implementing `std::error::Error` can be automatically converted and returned. ```Rust use anyhow::Result; fn get_cluster_info() -> Result { let config = std::fs::read_to_string("cluster.json")?; let map: ClusterMap = serde_json::from_str(&config)?; Ok(map) } ``` -------------------------------- ### Rust: Integrate with thiserror for Custom Error Types Source: https://docs.rs/anyhow/latest/anyhow/index Demonstrates how to define custom error types using the `thiserror` crate and implement `std::error::Error` for them, making them compatible with `anyhow` for seamless integration. ```Rust use thiserror::Error; #[derive(Error, Debug)] pub enum FormatError { #[error("Invalid header (expected {expected:?}, got {found:?})")] InvalidHeader { expected: String, found: String, }, #[error("Missing attribute: {0}")] MissingAttribute(String), } ``` -------------------------------- ### Rust: Conditional Error Return with ensure! Macro Source: https://docs.rs/anyhow/latest/anyhow/index Demonstrates the `ensure!` macro for returning an error early if a specific condition is not met, improving code readability for validation checks. ```Rust ensure!(condition, "Error message if condition is false"); ``` -------------------------------- ### Rust: Chain Operations with `and` Source: https://docs.rs/anyhow/latest/anyhow/type The `and` function returns the second `Result` if the first is `Ok`, otherwise returns the `Err` of the first. Arguments are eagerly evaluated. ```Rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Rust Result unwrap_or_default Method Source: https://docs.rs/anyhow/latest/anyhow/type Illustrates the `unwrap_or_default` method, which returns the Ok value or the default value for the type if the Result is an Err. This is useful for fallbacks. ```Rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Display Representations of Error Source: https://docs.rs/anyhow/latest/anyhow/struct Demonstrates how to display error information using different formatting specifiers. '{:#}' shows the cause chain, '{:?}' includes the backtrace, and '{:#?}' provides a struct-style Debug representation. ```Rust Failed to read instrs from ./path/to/instrs.json ``` ```Rust Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2) ``` ```Rust Error: Failed to read instrs from ./path/to/instrs.json Caused by: No such file or directory (os error 2) Stack backtrace: 0: ::ext_context at /git/anyhow/src/backtrace.rs:26 1: core::result::Result::map_err at /git/rustc/src/libcore/result.rs:596 2: anyhow::context:: for core::result::Result>::with_context at /git/anyhow/src/context.rs:58 3: testing::main at src/main.rs:5 4: std::rt::lang_start at /git/rustc/src/libstd/rt.rs:61 5: main 6: __libc_start_main 7: _start ``` ```Rust Error { context: "Failed to read instrs from ./path/to/instrs.json", source: Os { code: 2, kind: NotFound, message: "No such file or directory", }, } ``` -------------------------------- ### Rust Function: context Source: https://docs.rs/anyhow/latest/anyhow/trait The `context` method from the `Context` trait in the anyhow crate. It wraps an error value with additional, immediately evaluated context. ```Rust fn context(self, context: C) -> Result where C: Display + Send + Sync + 'static, Wrap the error value with additional context. ``` -------------------------------- ### Result::copied Method for &T Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates the `copied` method for `Result<&T, E>`, which maps a `Result` containing a reference to a value to a `Result` containing the copied value. This requires the type `T` to implement the `Copy` trait. ```Rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Add Context to Option in Rust Source: https://docs.rs/anyhow/latest/anyhow/trait Demonstrates adding contextual error messages to an `Option` using the `anyhow::Context` trait. The `context()` method is used to provide a static string as context when unwrapping the `Option`. ```Rust use anyhow::{Context, Result}; fn maybe_get() -> Option { // Placeholder for a function that might return None None } fn demo() -> Result<()> { let t = maybe_get::().context("there is no T")?; Ok(()) } ``` -------------------------------- ### Result::cloned Method for &mut T Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates the `cloned` method for `Result<&mut T, E>`, which maps a `Result` containing a mutable reference to a value to a `Result` containing a cloned value. This requires the type `T` to implement the `Clone` trait. ```Rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Result::cloned Method for &T Source: https://docs.rs/anyhow/latest/anyhow/type Illustrates the `cloned` method for `Result<&T, E>`, which maps a `Result` containing a reference to a value to a `Result` containing a cloned value. This requires the type `T` to implement the `Clone` trait. ```Rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Add Dynamic Context to Result in Rust Source: https://docs.rs/anyhow/latest/anyhow/trait Demonstrates using `with_context` to add dynamically generated context to a `Result`. The closure provides the context message, allowing for runtime-specific error details. ```Rust use anyhow::{Context, Result}; use std::fmt::Display; use std::error::StdError; // Assuming a function that returns a Result with a compatible error type fn operation_that_might_fail() -> Result { // Placeholder for an operation that could fail unimplemented!() } fn demo_with_context_result() -> Result { let error_code = 500; let result: Result = operation_that_might_fail(); result.with_context(|| format!("Operation failed with status code {}", error_code)) } ``` -------------------------------- ### Rust: Downcast Errors with anyhow Source: https://docs.rs/anyhow/latest/anyhow/index Illustrates how to downcast an `anyhow::Error` to a specific error type using `downcast_ref()`. This allows for pattern matching and handling of specific error variants, such as `DataStoreError`. ```Rust // If the error was caused by redaction, then return a // tombstone instead of the content. match root_cause.downcast_ref::() { Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)), None => Err(error), } ``` -------------------------------- ### Rust Result unwrap_err Method Source: https://docs.rs/anyhow/latest/anyhow/type Demonstrates the `unwrap_err` method to retrieve the Err value from a Result. It panics if the Result is Ok. This is useful when you expect an error. ```Rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```Rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Rust: Convert to String Source: https://docs.rs/anyhow/latest/anyhow/struct Converts the value into a `String`. This implementation requires the type to implement the `Display` trait, enabling string representation. ```rust fn to_string(&self) -> String where Self: Display + ?Sized ``` -------------------------------- ### Rust: Provide Default on Error with `or` Source: https://docs.rs/anyhow/latest/anyhow/type The `or` function returns the `Ok` value of the first `Result` if it's `Ok`, otherwise returns the second `Result`. Arguments are eagerly evaluated. ```Rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Add Dynamic Context to Option in Rust Source: https://docs.rs/anyhow/latest/anyhow/trait Illustrates using `with_context` to add context to an `Option` where the context message is generated dynamically by a closure. This is useful when the context depends on runtime values. ```Rust use anyhow::{Context, Result}; use std::fmt::Display; fn maybe_get() -> Option { // Placeholder for a function that might return None None } fn demo_with_context_option() -> Result { let value = 10; let t = maybe_get::().with_context(|| format!("Value was {}, but no T found", value))?; Ok(t) } ``` -------------------------------- ### Map Result to Default Value (Rust) Source: https://docs.rs/anyhow/latest/anyhow/type The `map_or_default` method maps a Result to a U type by applying a function to the Ok value, or returns the default value of U if the Result is Err. This is a nightly-only experimental API. ```Rust #![feature(result_option_map_or_default)] let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Access Backtrace (Rust) Source: https://docs.rs/anyhow/latest/anyhow/struct Retrieves the backtrace associated with an anyhow error. Backtraces are captured when specific environment variables (`RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1`) are set. ```Rust anyhow = { version = "1.0", features = ["backtrace"] } ``` -------------------------------- ### Iterate Over Ok Value (Rust) Source: https://docs.rs/anyhow/latest/anyhow/type The `iter` method returns an iterator that yields a reference to the contained value if the Result is Ok, otherwise it yields nothing. This is useful for treating Result like an optional collection. ```Rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Create Error from Message (Rust) Source: https://docs.rs/anyhow/latest/anyhow/struct Creates a new error object from a printable error message. This is equivalent to using the `anyhow!` macro but can be useful in function contexts like iterator combinators. ```Rust use anyhow::{Error, Result}; use futures::stream::{Stream, StreamExt, TryStreamExt}; async fn demo(stream: S) -> Result> where S: Stream, { stream .then(ffi::do_some_work) // returns Result .map_err(Error::msg) // Use Error::msg to convert &str to anyhow::Error .try_collect() .await } ``` -------------------------------- ### Rust Macro ensure Definition Source: https://docs.rs/anyhow/latest/anyhow/macro Defines the 'ensure' macro in Rust, which allows for early return of an error if a condition is false. It supports literal messages, formatted messages, and custom error types. ```Rust macro_rules! ensure { ($cond:expr $(,)?) => { ... }; ($cond:expr, $msg:literal $(,)?) => { ... }; ($cond:expr, $err:expr $(,)?) => { ... }; ($cond:expr, $fmt:expr, $($arg:tt)*) => { ... }; } ``` -------------------------------- ### Rust Result is_ok Source: https://docs.rs/anyhow/latest/anyhow/type Checks if the Result is Ok. Returns true if the result is Ok, false otherwise. ```Rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Rust: Convert Result to Error without Panic Source: https://docs.rs/anyhow/latest/anyhow/type The `into_err` function returns the contained `Err` value, never panicking. It's a nightly-only experimental API useful as a maintainability safeguard. ```Rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Rust Result as_mut Source: https://docs.rs/anyhow/latest/anyhow/type Converts a mutable reference to a Result<&mut T, &mut E> into a Result<&mut T, &mut E>. Allows modification of the contained value or error. ```Rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Rust Result err Source: https://docs.rs/anyhow/latest/anyhow/type Converts a Result into an Option, consuming the Result and discarding the success value if present. ```Rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Result::copied Method for &mut T Source: https://docs.rs/anyhow/latest/anyhow/type Shows the `copied` method for `Result<&mut T, E>`, which maps a `Result` containing a mutable reference to a value to a `Result` containing the copied value. This requires the type `T` to implement the `Copy` trait. ```Rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Rust Result is_ok_and Source: https://docs.rs/anyhow/latest/anyhow/type Checks if the Result is Ok and if the contained value satisfies a given predicate. Returns true if both conditions are met, false otherwise. ```Rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Inspect Ok Value (Rust) Source: https://docs.rs/anyhow/latest/anyhow/type The `inspect` method calls a provided closure with a reference to the contained value if the Result is Ok, returning the original Result. It's used for side effects. ```Rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Rust Result map Source: https://docs.rs/anyhow/latest/anyhow/type Maps a Result to Result by applying a function to the contained Ok value, leaving Err values untouched. Useful for composing operations on Results. ```Rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Rust: Clone Result Source: https://docs.rs/anyhow/latest/anyhow/type Implements the Clone trait for Result, allowing for duplication of the value if both the Ok and Err types are themselves Clone. ```Rust impl Clone for Result where T: Clone, E: Clone, { fn clone(&self) -> Result; fn clone_from(&mut self, source: &Result); } ``` -------------------------------- ### Convert Result to Result<&T::Target, &E> (Rust) Source: https://docs.rs/anyhow/latest/anyhow/type The `as_deref` method converts a Result containing a type that implements Deref into a Result containing a reference to the dereferenced target type. It handles both Ok and Err variants. ```Rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Rust: Iterate over Result value Source: https://docs.rs/anyhow/latest/anyhow/type Implements IntoIterator for Result, enabling iteration over the contained value. The iterator yields the Ok value once if present, otherwise it yields nothing. ```Rust impl IntoIterator for Result { type Item = T; fn into_iter(self) -> IntoIter; } // Example 1: Iterating over Ok let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); // Example 2: Iterating over Err let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### Map Result with Fallback Function (Rust) Source: https://docs.rs/anyhow/latest/anyhow/type The `map_or_else` method maps a Result to a new type by applying a fallback function to the Err value or a mapping function to the Ok value. This allows for lazy evaluation of arguments. ```Rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` -------------------------------- ### Rust Result expect_err Method Source: https://docs.rs/anyhow/latest/anyhow/type Shows the `expect_err` method, which returns the Err value from a Result, panicking with a custom message if it's an Ok. This is useful for asserting that an operation failed. ```Rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Rust: Into Target Type Source: https://docs.rs/anyhow/latest/anyhow/struct Converts the type `T` into another type `U` using the `From` implementation for `U`. This is a common pattern for type transformations. ```rust fn into(self) -> U where U: From ``` -------------------------------- ### Rust Function: with_context Source: https://docs.rs/anyhow/latest/anyhow/trait The `with_context` method from the `Context` trait in the anyhow crate. It wraps an error value with additional context that is evaluated lazily only when an error occurs. ```Rust fn with_context(self, f: F) -> Result where C: Display + Send + Sync + 'static, F: FnOnce() -> C, Wrap the error value with additional context that is evaluated lazily only once an error does occur. ``` -------------------------------- ### Rust: Hash Result Source: https://docs.rs/anyhow/latest/anyhow/type Implements the Hash trait for Result, allowing hashing of the contained value if both the Ok and Err types implement Hash. Also provides a method to hash slices of Results. ```Rust impl where T: Hash, E: Hash, { fn hash<__H>(&self, state: &mut __H) where __H: Hasher; fn hash_slice(data: &[Self], state: &mut H) where H: Hasher, Self: Sized; } ``` -------------------------------- ### Add Context to Error (Rust) Source: https://docs.rs/anyhow/latest/anyhow/struct Wraps an existing error value with additional context, typically a formatted string. This is useful for providing more information when an error is propagated. ```Rust use anyhow::Result; use std::fs::File; use std::path::Path; struct ParseError { line: usize, column: usize, } fn parse_impl(file: File) -> Result { // ... implementation details ... unimplemented!() } pub fn parse(path: impl AsRef) -> Result { let file = File::open(&path)?; parse_impl(file).map_err(|error| { let context = format!( "only the first {} lines of {} are valid", error.line, path.as_ref().display(), ); anyhow::Error::new(error).context(context) // Add context to the error }) } ``` -------------------------------- ### Rust: Chain Fallible Operations with `and_then` Source: https://docs.rs/anyhow/latest/anyhow/type The `and_then` function calls a closure if the `Result` is `Ok`, returning the closure's `Result`. Otherwise, it returns the `Err` value. It's useful for chaining fallible operations. ```Rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` ```Rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ```