alloy_consensus/
error.rs

1//! Helper errors.
2
3use alloc::{borrow::Cow, boxed::Box, string::ToString};
4
5/// Helper type that is [`core::error::Error`] and wraps a value and an error message.
6///
7/// This can be used to return an object as part of an `Err` and is used for fallible conversions.
8#[derive(Debug, thiserror::Error)]
9#[error("{msg}")]
10pub struct ValueError<T> {
11    msg: Cow<'static, str>,
12    value: Box<T>,
13}
14
15impl<T> ValueError<T> {
16    /// Creates a new error with the given value and error message.
17    pub fn new(value: T, msg: impl core::fmt::Display) -> Self {
18        Self { msg: Cow::Owned(msg.to_string()), value: Box::new(value) }
19    }
20
21    /// Creates a new error with a static error message.
22    pub fn new_static(value: T, msg: &'static str) -> Self {
23        Self { msg: Cow::Borrowed(msg), value: Box::new(value) }
24    }
25
26    /// Converts the value to the given alternative that is `From<T>`.
27    pub fn convert<U>(self) -> ValueError<U>
28    where
29        U: From<T>,
30    {
31        self.map(U::from)
32    }
33
34    /// Maps the error's value with the given closure.
35    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ValueError<U> {
36        ValueError { msg: self.msg, value: Box::new(f(*self.value)) }
37    }
38
39    /// Consumes the type and returns the underlying value.
40    pub fn into_value(self) -> T {
41        *self.value
42    }
43
44    /// Returns a reference to the value.
45    pub const fn value(&self) -> &T {
46        &self.value
47    }
48}