### Example: Create Rust 'Exn' from Error using 'ensure' macro Source: https://docs.rs/exn/latest/exn/macro.ensure_search= Demonstrates how to use the 'ensure' macro to create an 'Exn' from an error. This example defines a custom error type 'PermissionDenied' and uses 'ensure!' to conditionally return it. ```rust use std::error::Error; use std::fmt; use exn::ensure; #[derive(Debug)] struct PermissionDenied(User, Resource); impl fmt::Display for PermissionDenied { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "permission denied") } } impl Error for PermissionDenied {} ensure!( has_permission(&user, &resource), PermissionDenied(user, resource), ); ``` -------------------------------- ### Example of using bail! macro with std::fs in Rust Source: https://docs.rs/exn/latest/exn/macro.bail_search= This example demonstrates how to use the `bail!` macro from the exn crate to handle potential errors when reading a file using `std::fs::read_to_string`. If an error occurs, `bail!(err)` will return the error. ```Rust use std::fs; use exn::bail; match fs::read_to_string("/path/to/file") { Ok(content) => println!("file contents: {content}"), Err(err) => bail!(err), } ``` -------------------------------- ### Exn::try_from Method Source: https://docs.rs/exn/latest/exn/trait.Error_search=u32+-%3E+bool Demonstrates the `try_from` method for the `Exn` type, showing its conversion capabilities from `u32` to a generic type `T` where `T` matches `bool` in this specific example. ```APIDOC ## Method `exn::Exn::try_from` ### Description Attempts to convert a `u32` into an `Exn` of a specific type `T`, where `T` is constrained to `bool` in this usage example. ### Signature `exn::Exn::try_from(u32) -> Result` where `u32` matches `U` `bool` matches `T` ``` -------------------------------- ### Example: Frame::try_from with u32 and bool - Rust Source: https://docs.rs/exn/latest/exn/struct.Frame_search=u32+-%3E+bool Shows an example of calling `exn::Frame::try_from`, specifically converting a `u32` to a `bool`. This highlights how the `try_from` method on the `Frame` struct can be used with these concrete types. ```rust method exn::Frame::try_from **U** -> Result<**T** > where u32 matches **U** bool matches **T** ``` -------------------------------- ### Example: Exn::try_from with u32 and bool - Rust Source: https://docs.rs/exn/latest/exn/struct.Frame_search=u32+-%3E+bool Illustrates the usage of `exn::Exn::try_from` where a `u32` is being converted to a `bool`. This demonstrates a specific generic type instantiation for the conversion method. ```rust method exn::Exn::try_from **U** -> Result<**T** > where u32 matches **U** bool matches **T** ``` -------------------------------- ### Type Inference Example for try_from Methods in Rust Source: https://docs.rs/exn/latest/exn/trait.OptionExt_search=u32+-%3E+bool Illustrates type inference for the try_from methods within the exn::Exn and exn::Frame types. It shows how u32 can be inferred as the input type U and bool as the output type T for the Result. ```Rust // Example for exn::Exn::try_from // U is inferred as u32, T is inferred as bool // let result: Result = exn::Exn::try_from(some_u32_value); // Example for exn::Frame::try_from // U is inferred as u32, T is inferred as bool // let result: Result = exn::Frame::try_from(some_u32_value); ``` -------------------------------- ### Defining and Handling Custom Errors with Exn Source: https://docs.rs/exn/latest/src/exn/lib.rs_search=u32+-%3E+bool This example demonstrates how to define custom error types (structs and enums) and use the `exn` crate's `bail!` macro to create errors. It also shows how to handle these errors using `ResultExt::or_raise` and how the `exn` crate formats the error chain for better debugging. ```rust // Copyright 2025 FastLabs Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A context-aware concrete Error type built on `std::error::Error` //! //! # Examples //! //! ``` //! use exn::Result; //! use exn::ResultExt; //! use exn::bail; //! //! // It's recommended to define errors as structs. Exn will maintain the error tree automatically. //! #[derive(Debug)] //! struct LogicError(String); //! //! impl std::fmt::Display for LogicError { //! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { //! write!(f, "logic error: {}", self.0) //! } //! } //! //! impl std::error::Error for LogicError {} //! //! fn do_logic() -> Result<(), LogicError> { //! bail!(LogicError("0 == 1".to_string())); //! } //! //! // Errors can be enum but notably don't need to chain source error. //! #[derive(Debug)] //! enum AppError { //! Fatal { consequences: &'static str }, //! Trivial, //! } //! //! impl std::fmt::Display for AppError { //! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { //! match self { //! AppError::Fatal { consequences } => write!(f, "fatal error: {consequences}"), //! AppError::Trivial => write!(f, "trivial error"), //! } //! } //! } //! //! impl std::error::Error for AppError {} //! //! fn main() { //! if let Err(err) = do_logic().or_raise(|| AppError::Fatal { //! consequences: "math no longer works", //! }) { //! eprintln!("{err:?}"); //! } //! } //! ``` //! //! The above program will print an error message like: //! //! ```text //! fatal error: math no longer works, at exn/src/lib.rs:44:16 //! | //! |-> logic error: 0 == 1, at exn/src/lib.rs:40:5 //! ``` #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(missing_docs)] mod debug; mod display; mod impls; mod macros; mod option; mod result; pub use self::impls::Exn; pub use self::impls::Frame; pub use self::option::OptionExt; pub use self::result::Result; pub use self::result::ResultExt; /// A trait bound of the supported error type of [`Exn`]. pub trait Error: std::error::Error + std::any::Any + Send + Sync + 'static { /// Raise this error as a new exception. #[track_caller] fn raise(self) -> Exn where Self: Sized, { Exn::new(self) } } impl Error for T where T: std::error::Error + std::any::Any + Send + Sync + 'static {} /// Equivalent to `Ok::<_, Exn>(value)`. /// /// This simplifies creation of an `exn::Result` in places where type inference cannot deduce the /// `E` type of the result — without needing to write `Ok::<_, Exn>(value)`. /// /// One might think that `exn::Result::Ok(value)` would work in such cases, but it does not. /// /// ```console /// error[E0282]: type annotations needed for `std::result::Result` /// --> src/main.rs:11:13 /// | /// 11 | let _ = exn::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 /// ``` #[expect(non_snake_case)] pub fn Ok(value: T) -> Result { Result::Ok(value) } ``` -------------------------------- ### Get Metadata with Error Handling using Result::and_then Source: https://docs.rs/exn/latest/exn/type.Result_search=u32+-%3E+bool Shows an example of using `and_then` to chain metadata retrieval operations. This snippet accesses file metadata and attempts to get the modified time, handling potential errors like 'not found' or I/O issues. It demonstrates how to chain fallible operations on path metadata. ```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); ``` -------------------------------- ### Rust Error Handling Example with Custom Errors and ResultExt Source: https://docs.rs/exn/latest/exn/index Demonstrates defining custom error structs and enums, implementing std::fmt::Display and std::error::Error, and using ResultExt's or_raise method to handle errors within a Result. This showcases how 'exn' helps build an error tree for better context. ```rust use exn::Result; use exn::ResultExt; use exn::bail; // It's recommended to define errors as structs. Exn will maintain the error tree automatically. #[derive(Debug)] struct LogicError(String); impl std::fmt::Display for LogicError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "logic error: {}", self.0) } } impl std::error::Error for LogicError {} fn do_logic() -> Result<(), LogicError> { bail!(LogicError("0 == 1".to_string())); } // Errors can be enum but notably don't need to chain source error. #[derive(Debug)] enum AppError { Fatal { consequences: &'static str }, Trivial, } impl std::fmt::Display for AppError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { AppError::Fatal { consequences } => write!(f, "fatal error: {consequences}"), AppError::Trivial => write!(f, "trivial error"), } } } impl std::error::Error for AppError {} fn main() { if let Err(err) = do_logic().or_raise(|| AppError::Fatal { consequences: "math no longer works", }) { eprintln!("{err:?}"); } } ``` -------------------------------- ### Exn and Frame TryFrom Signatures (Rust) Source: https://docs.rs/exn/latest/exn/struct.Exn_search=u32+-%3E+bool Shows the generic signatures for `try_from` methods within `exn::Exn` and `exn::Frame`. These signatures indicate a conversion from a type `U` to a result containing type `T`, with specific examples showing `u32` mapping to `U` and `bool` mapping to `T`. ```rust method exn::Exn::try_from **U** -> Result<**T** > where u32 matches **U** bool matches **T** ``` ```rust method exn::Frame::try_from **U** -> Result<**T** > where u32 matches **U** bool matches **T** ``` -------------------------------- ### Safely Get Ok Value (Nightly) in Rust Source: https://docs.rs/exn/latest/exn/type.Result Introduces the experimental `into_ok()` method (nightly only) that returns the `Ok` value without panicking. This serves as a compile-time safeguard against unexpected error types. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Error Handling with Exn Crate in Rust Source: https://docs.rs/exn/latest/exn/index_search= Demonstrates defining custom errors as structs and enums, using the `bail!` macro to create and return errors, and the `or_raise` method to add context to errors. This example showcases the crate's ability to build an error tree for detailed error reporting. ```rust use exn::Result; use exn::ResultExt; use exn::bail; // It's recommended to define errors as structs. Exn will maintain the error tree automatically. #[derive(Debug)] struct LogicError(String); impl std::fmt::Display for LogicError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "logic error: {}", self.0) } } impl std::error::Error for LogicError {} fn do_logic() -> Result<(), LogicError> { bail!(LogicError("0 == 1".to_string())); } // Errors can be enum but notably don't need to chain source error. #[derive(Debug)] enum AppError { Fatal { consequences: &'static str }, Trivial, } impl std::fmt::Display for AppError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { AppError::Fatal { consequences } => write!(f, "fatal error: {consequences}"), AppError::Trivial => write!(f, "trivial error"), } } } impl std::error::Error for AppError {} fn main() { if let Err(err) = do_logic().or_raise(|| AppError::Fatal { consequences: "math no longer works", }) { eprintln!("{err:?}"); } } ``` -------------------------------- ### Simplified Ok Result Creation with Exn Source: https://docs.rs/exn/latest/src/exn/lib.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to use the `exn::Ok` function to create a Result with an error type inferred as `Exn`, simplifying code where type annotations would otherwise be necessary. ```rust /// Equivalent to `Ok::<_, Exn>(value)`. /// /// This simplifies creation of an `exn::Result` in places where type inference cannot deduce the /// `E` type of the result — without needing to write `Ok::<_, Exn>(value)`. /// /// One might think that `exn::Result::Ok(value)` would work in such cases, but it does not. /// /// ```console /// error[E0282]: type annotations needed for `std::result::Result` /// --> src/main.rs:11:13 /// | /// 11 | let _ = exn::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 /// ``` #[expect(non_snake_case)] pub fn Ok(value: T) -> Result { Result::Ok(value) } ``` -------------------------------- ### Basic Type Conversions (Rust) Source: https://docs.rs/exn/latest/exn/struct.Exn_search=u32+-%3E+bool Illustrates fundamental conversion traits. `From` for `T` allows an identity conversion. `ToString` enables converting types that implement `Display` into strings. `TryFrom` and `TryInto` offer fallible conversion mechanisms. ```rust impl From for T fn from(t: T) -> T ``` ```rust impl ToString for T where T: Display + ?Sized fn to_string(&self) -> String ``` ```rust impl TryFrom for T where U: Into type Error = Infallible fn try_from(value: U) -> Result>::Error> ``` ```rust impl TryInto for T where U: TryFrom type Error = >::Error fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Simplified `Ok` Result Creation with `exn` in Rust Source: https://docs.rs/exn/latest/src/exn/lib.rs_search=std%3A%3Avec Provides a helper function `Ok` that simplifies the creation of `exn::Result` values. This function is particularly useful in scenarios where type inference might struggle to deduce the error type `E`, avoiding the need for explicit type annotations. ```rust /// Equivalent to `Ok::<_, Exn>(value)`. /// /// This simplifies creation of an `exn::Result` in places where type inference cannot deduce the /// `E` type of the result — without needing to write `Ok::<_, Exn>(value)`. /// /// One might think that `exn::Result::Ok(value)` would work in such cases, but it does not. /// /// ```console /// error[E0282]: type annotations needed for `std::result::Result` /// --> src/main.rs:11:13 /// | /// 11 | let _ = exn::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 /// ``` #[expect(non_snake_case)] pub fn Ok(value: T) -> Result { Result::Ok(value) } ``` -------------------------------- ### into_ok Source: https://docs.rs/exn/latest/exn/type.Result_search=std%3A%3Avec Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ```APIDOC ## GET /into_ok ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. This is a nightly-only experimental API. ### Method GET ### Endpoint /into_ok ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value to process. ### Response #### Success Response (200) - **value** (T) - The contained Ok value. ### Request Example ```json { "value": "Ok(\"this is fine\")" } ``` ### Response Example ```json { "value": "this is fine" } ``` ``` -------------------------------- ### Result::report Source: https://docs.rs/exn/latest/exn/type.Result_search= Is called to get the representation of the Result as an ExitCode. This status code is returned to the operating system. ```APIDOC ## POST /websites/rs_exn/report ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Method POST ### Endpoint /websites/rs_exn/report ### Parameters #### Path Parameters - **self** (Result) - Required - The Result to report. ### Request Body ```json { "self": { "Ok": "success_value" } } ``` ### Response #### Success Response (200) - **exit_code** (ExitCode) - The exit code representing the Result. #### Response Example ```json { "exit_code": 0 } ``` ``` -------------------------------- ### Exn Struct and Methods Source: https://docs.rs/exn/latest/exn/struct.Exn Provides details on the Exn struct, its constructor, and methods for managing error hierarchies. ```APIDOC ## Struct Exn ### Description An exception type that can hold an error tree and additional context. ### Methods #### `new(error: E) -> Self` **Description**: Create a new exception with the given error. This will automatically walk the source chain of the error and add them as children frames. **Method**: `pub fn new` **Parameters**: * `error` (E) - Required - The error to initialize the exception with. #### `from_iter(children: I, err: E) -> Self` where T: Error, I: IntoIterator, I::Item: Into> **Description**: Create a new exception with the given error and children. **Method**: `pub fn from_iter` **Parameters**: * `children` (I) - Required - An iterator of child exceptions. * `err` (E) - Required - The root error for this exception. #### `raise(self, err: T) -> Exn` **Description**: Raise a new exception; this will make the current exception a child of the new one. **Method**: `pub fn raise` **Parameters**: * `err` (T) - Required - The new error to raise. #### `as_error(&self) -> &E` **Description**: Return the current exception. **Method**: `pub fn as_error` **Parameters**: None #### `as_frame(&self) -> &Frame` **Description**: Return the underlying exception frame. **Method**: `pub fn as_frame` **Parameters**: None ``` -------------------------------- ### Get Exception Frame in Exn in Rust Source: https://docs.rs/exn/latest/exn/struct.Exn_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves a reference to the underlying exception frame associated with the Exn struct. This can be useful for inspecting the structure or metadata of the exception. ```rust pub fn as_frame(&self) -> &Frame ``` -------------------------------- ### Get Source Location of Frame - Rust Source: https://docs.rs/exn/latest/exn/struct.Frame_search=u32+-%3E+bool Retrieves the source code location where a 'Frame' was created. The returned 'Location' is a static reference, indicating it's compile-time known. ```rust pub fn location(&self) -> &'static Location<'static> Return the source code location where this exception frame was created. ``` -------------------------------- ### Rust: Create exn::Result using Ok function Source: https://docs.rs/exn/latest/exn/fn.Ok_search=std%3A%3Avec Demonstrates the 'Ok' function in the exn crate, which simplifies the creation of an exn::Result. It's particularly useful when type inference struggles with the generic 'E' type, avoiding the need for explicit type annotations like `Ok::<_, Exn>(value)`. ```Rust pub fn Ok(value: T) -> Result ``` -------------------------------- ### Unwrapping `Result` with a Default Value in Rust Source: https://docs.rs/exn/latest/exn/type.Result Shows how to use `unwrap_or` to get the `Ok` value from a `Result` or a specified default value if it's an `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); ``` -------------------------------- ### Frame Struct Methods - Rust Source: https://docs.rs/exn/latest/exn/struct.Frame Provides methods for interacting with the `Frame` struct. These include retrieving the error as `Any` or `Error`, accessing the source code location, and getting child frames. ```rust pub fn as_any(&self) -> &dyn Any ``` ```rust pub fn as_error(&self) -> &dyn Error ``` ```rust pub fn location(&self) -> &'static Location<'static> ``` ```rust pub fn children(&self) -> &[Frame] ``` -------------------------------- ### Get Underlying Error in Exn in Rust Source: https://docs.rs/exn/latest/exn/struct.Exn_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a reference to the underlying error (of type E) contained within the Exn struct. This allows access to the specific error that triggered the exception. ```rust pub fn as_error(&self) -> &E ``` -------------------------------- ### into_ok() Source: https://docs.rs/exn/latest/exn/type.Result_search=u32+-%3E+bool Returns the contained Ok value, never panics. Requires the error type to be convertible to !. ```APIDOC ## GET /result/into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for, acting as a maintainability safeguard. ### Method GET ### Endpoint `/result/into_ok` ### Parameters #### Query Parameters - **result** (Result) - Required - The Result object. ### Request Example ```json { "result": "Ok(\"hello\")" } ``` ### Response #### Success Response (200) - **value** (T) - The contained Ok value. #### Response Example ```json { "value": "hello" } ``` ``` -------------------------------- ### Result::as_deref Source: https://docs.rs/exn/latest/exn/type.Result_search=u32+-%3E+bool Converts `Result` to `Result<&::Target, &E>` by coercing the `Ok` variant via `Deref`. Useful for getting references to the inner value without consuming the `Result`. ```APIDOC ## Result::as_deref ### Description Converts `Result` to `Result<&::Target, &E>` by coercing the `Ok` variant via `Deref`. Useful for getting references to the inner value without consuming the `Result`. ### Method `as_deref` ### Endpoint N/A (Method on Result type) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```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); ``` ### Response #### Success Response (200) N/A (Method returns a Result) #### Response Example ```rust // For Ok(String), returns Ok(&str) // For Err(u32), returns Err(&u32) ``` ``` -------------------------------- ### Implement Display and Debug for Exn in Rust Source: https://docs.rs/exn/latest/exn/struct.Exn_search=std%3A%3Avec Demonstrates the implementation of the `Debug` and `Display` traits for the `Exn` struct. These implementations allow for formatted output of `Exn` instances, enabling easier debugging and user-friendly error reporting. ```rust impl Debug for Exn fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` ```rust impl Display for Exn fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Get references from Result (Rust) Source: https://docs.rs/exn/latest/exn/type.Result The `as_ref` method converts a reference to a Result into a Result of references. It allows inspecting the contents of a Result without consuming it. The original Result remains unchanged. ```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")); ``` -------------------------------- ### and() Source: https://docs.rs/exn/latest/exn/type.Result_search=u32+-%3E+bool Returns the second result if the first is Ok, otherwise returns the first result's Err. ```APIDOC ## GET /result/and ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. Arguments passed to `and` are eagerly evaluated. ### Method GET ### Endpoint `/result/and` ### Parameters #### Query Parameters - **self_result** (Result) - Required - The first Result object. - **other_result** (Result) - Required - The second Result object to return if `self_result` is Ok. ### Request Example ```json { "self_result": "Ok(2)", "other_result": "Ok(\"foo\")" } ``` ### Response #### Success Response (200) - **result** (Result) - The `other_result` if `self_result` was Ok, otherwise the Err from `self_result`. #### Response Example ```json { "result": "Ok(\"foo\")" } ``` ``` -------------------------------- ### Result Conversion Methods Source: https://docs.rs/exn/latest/exn/type.Result_search= Demonstrates methods for converting a Result into an Option, consuming the original Result. ```APIDOC ## Result Conversion Methods ### Description Methods to convert a `Result` into an `Option` or `Option`. ### Methods #### `fn ok(self) -> Option` Converts `self` into an `Option`, consuming `self`, and discarding the error, if any. ##### §Examples ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` #### `fn err(self) -> Option` Converts `self` into an `Option`, consuming `self`, and discarding the success value, if any. ##### §Examples ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` ``` -------------------------------- ### Frame Methods - Rust Source: https://docs.rs/exn/latest/exn/struct.Frame_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods for the `Frame` struct to access exception details. These include getting the error as `Any` or `Error` traits, retrieving the source code location, and accessing child exceptions. ```rust pub fn as_any(&self) -> &dyn Any ``` ```rust pub fn as_error(&self) -> &dyn Error ``` ```rust pub fn location(&self) -> &'static Location<'static> ``` ```rust pub fn children(&self) -> &[Frame] ``` -------------------------------- ### Frame Trait Implementations Source: https://docs.rs/exn/latest/exn/struct.Frame_search= Documentation for trait implementations for the Frame struct. ```APIDOC ## Trait Implementations for Frame ### `impl Debug for Frame` #### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` * **Description**: Formats the value using the given formatter. * **Method**: `fn` * **Return Type**: `Result` ### `impl Freeze for Frame` (No methods to document for this auto trait) ### `impl !RefUnwindSafe for Frame` (No methods to document for this auto trait) ### `impl Send for Frame` (No methods to document for this auto trait) ### `impl Sync for Frame` (No methods to document for this auto trait) ### `impl Unpin for Frame` (No methods to document for this auto trait) ### `impl !UnwindSafe for Frame` (No methods to document for this auto trait) ### `impl Any for T` (Blanket Implementation) #### `fn type_id(&self) -> TypeId` * **Description**: Gets the `TypeId` of `self`. * **Method**: `fn` * **Return Type**: `TypeId` ### `impl Borrow for T` (Blanket Implementation) #### `fn borrow(&self) -> &T` * **Description**: Immutably borrows from an owned value. * **Method**: `fn` * **Return Type**: `&T` ### `impl BorrowMut for T` (Blanket Implementation) #### `fn borrow_mut(&mut self) -> &mut T` * **Description**: Mutably borrows from an owned value. * **Method**: `fn` * **Return Type**: `&mut T` ### `impl From for T` (Blanket Implementation) #### `fn from(t: T) -> T` * **Description**: Returns the argument unchanged. * **Method**: `fn` * **Return Type**: `T` ### `impl Into for T` (Blanket Implementation) #### `fn into(self) -> U` * **Description**: Calls `U::from(self)`. This conversion is whatever the implementation of `From for U` chooses to do. * **Method**: `fn` * **Return Type**: `U` ### `impl TryFrom for T` (Blanket Implementation) #### `type Error = Infallible` * **Description**: The type returned in the event of a conversion error. #### `fn try_from(value: U) -> Result>::Error>` * **Description**: Performs the conversion. * **Method**: `fn` * **Return Type**: `Result>::Error>` ### `impl TryInto for T` (Blanket Implementation) #### `type Error = >::Error` * **Description**: The type returned in the event of a conversion error. #### `fn try_into(self) -> Result>::Error>` * **Description**: Performs the conversion. * **Method**: `fn` * **Return Type**: `Result>::Error>` ``` -------------------------------- ### report Method for Termination Trait (Rust) Source: https://docs.rs/exn/latest/exn/type.Result_search=std%3A%3Avec Converts a Result into an ExitCode. This is called to get the representation of the value as a status code to be returned to the operating system. Requires the Ok type T to implement the Termination trait. ```rust fn report(self) -> ExitCode ``` -------------------------------- ### ok() Source: https://docs.rs/exn/latest/exn/type.Result_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts a Result to an Option, discarding the error if any. Useful for extracting the successful value when needed. ```APIDOC ## pub fn ok(self) -> Option ### Description Converts from `Result` to `Option`. Converts `self` into an `Option`, consuming `self`, and discarding the error, if any. ### Method `pub fn ok(self) -> Option` ### Parameters None ### Request Example ``` let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ### Response #### Success Response (Example) - `Some(T)`: If the result was Ok, contains the wrapped value. - `None`: If the result was Err. ``` -------------------------------- ### Safely Get Err Value (Nightly) in Rust Source: https://docs.rs/exn/latest/exn/type.Result Presents the experimental `into_err()` method (nightly only) for retrieving the `Err` value without panicking. It acts as a compile-time check to prevent the `Ok` type from being introduced. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Exn Result Ok Constructor Source: https://docs.rs/exn/latest/exn/fn.Ok_search= Provides a simplified way to construct a Result type from the exn crate, especially when type inference for the error type `E` is challenging. ```APIDOC ## Function Ok ### Description Equivalent to `Ok::<_, Exn>(value)`. This simplifies creation of an `exn::Result` in places where type inference cannot deduce the `E` type of the result — without needing to write `Ok::<_, Exn>(value)`. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Source Code ```rust pub fn Ok(value: T) -> Result ``` ``` -------------------------------- ### Get mutable references from Result (Rust) Source: https://docs.rs/exn/latest/exn/type.Result The `as_mut` method converts a mutable reference to a Result into a Result of mutable references. This allows modifying the contained value if the Result is Ok, or the error value if it's Err, without taking ownership. ```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); ``` -------------------------------- ### Create New Exn Instance in Rust Source: https://docs.rs/exn/latest/exn/struct.Exn_search=std%3A%3Avec Provides methods for creating new instances of the Exn struct. `new` initializes an Exn with a given error, automatically including its source chain as child frames. `from_iter` allows creating an Exn with an initial error and a collection of child Exn instances. ```rust pub fn new(error: E) -> Self ``` ```rust pub fn from_iter(children: I, err: E) -> Self where T: Error, I: IntoIterator, I::Item: Into> ``` -------------------------------- ### impl OptionExt for Option Source: https://docs.rs/exn/latest/exn/trait.OptionExt_search=u32+-%3E+bool Implementation of the OptionExt trait for the standard Option type. ```APIDOC ## impl OptionExt for Option ### Associated Types #### type Some = T Description: The `Some` type is `T` when implementing for `Option`. ### Methods #### fn ok_or_raise(self, err: F) -> Result Description: Construct a new `Exn` on the `None` variant for `Option`. ### Method Signature ```rust impl OptionExt for Option where A: Error, F: FnOnce() -> A, { type Some = T; fn ok_or_raise(self, err: F) -> Result; } ``` ``` -------------------------------- ### exn::Result::Ok Function Source: https://docs.rs/exn/latest/exn/fn.Ok_search=std%3A%3Avec The `Ok` function simplifies the creation of an `exn::Result` by providing a convenient way to wrap a successful value. It is equivalent to `Ok::<_, Exn>(value)` and helps in cases where type inference might struggle to determine the `E` type. ```APIDOC ## Function Ok ### Description Equivalent to `Ok::<_, Exn>(value)`. This simplifies creation of an `exn::Result` in places where type inference cannot deduce the `E` type of the result — without needing to write `Ok::<_, Exn>(value)`. ### Method Rust Function ### Endpoint N/A (Rust function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust pub fn Ok(value: T) -> Result ``` ### Response #### Success Response Returns a `Result` enum where the variant is `Ok` containing the provided `value`. #### Response Example ```rust // Example usage within Rust code: // let success_result: exn::Result = exn::Ok(10); ``` ``` -------------------------------- ### Exn Result Ok Constructor Source: https://docs.rs/exn/latest/exn/fn.Ok This section details the `Ok` constructor for the `exn::Result` type, which is used to create a success variant of a Result. ```APIDOC ## Function Ok ### Description Equivalent to `Ok::<_, Exn>(value)`. This simplifies creation of an `exn::Result` in places where type inference cannot deduce the `E` type of the result — without needing to write `Ok::<_, Exn>(value)`. ### Method `Ok` (Constructor) ### Endpoint N/A (Function within a crate) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A (Function call, not an HTTP request) ### Response #### Success Response (N/A) Returns a `Result` where `T` is the type of `value` and `E` is inferred or specified as `Exn`. #### Response Example N/A (Function call, not an HTTP response) ### Example Usage ```rust use exn::Result; use std::error::Error; // Example where type inference might fail without the helper let success_result: Result = Ok(10); // Example illustrating the problem without the helper // let error_result = exn::Result::Ok(1); // This would cause a compile error due to E0282 // Using the helper function correctly fn create_ok_result(value: T) -> Result { Ok(value) } let specific_result: Result = create_ok_result("Success!".to_string()); ``` ### Error Handling This function itself does not produce errors; it creates a success `Result`. The surrounding code or the `E` type itself may handle errors. ```