Skip to main content

alephium_web3/
error.rs

1// Copyright 2018 - 2022 The Alephium Authors
2// This file is part of the alephium project.
3
4use thiserror::Error;
5
6/// Result type for the library
7pub type Result<T> = std::result::Result<T, Error>;
8
9/// Main error type for the Alephium Web3 library
10#[derive(Error, Debug)]
11pub enum Error {
12    #[error("Invalid address: {0}")]
13    InvalidAddress(String),
14
15    #[error("Invalid hex string: {0}")]
16    InvalidHex(String),
17
18    #[error("Invalid base58 string: {0}")]
19    InvalidBase58(String),
20
21    #[error("Invalid signature: {0}")]
22    InvalidSignature(String),
23
24    #[error("Invalid key: {0}")]
25    InvalidKey(String),
26
27    #[error("Codec error: {0}")]
28    CodecError(String),
29
30    #[error("API error: {0}")]
31    ApiError(String),
32
33    #[error("HTTP error: {0}")]
34    HttpError(#[from] reqwest::Error),
35
36    #[error("Serialization error: {0}")]
37    SerializationError(#[from] serde_json::Error),
38
39    #[error("Invalid transaction: {0}")]
40    InvalidTransaction(String),
41
42    #[error("Invalid contract: {0}")]
43    InvalidContract(String),
44
45    #[error("Invalid group index: {0}")]
46    InvalidGroupIndex(u8),
47
48    #[error("Insufficient balance")]
49    InsufficientBalance,
50
51    #[error("Invalid value: {0}")]
52    InvalidValue(String),
53
54    #[error("IO error: {0}")]
55    IoError(#[from] std::io::Error),
56
57    #[error("Cryptography error: {0}")]
58    CryptoError(String),
59
60    #[error("{0}")]
61    Other(String),
62}
63
64/// Traceable error that preserves the error chain
65#[derive(Debug)]
66pub struct TraceableError {
67    pub message: String,
68    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
69}
70
71impl std::fmt::Display for TraceableError {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{}", self.message)?;
74        if let Some(source) = &self.source {
75            write!(f, "\nCaused by: {}", source)?;
76        }
77        Ok(())
78    }
79}
80
81impl std::error::Error for TraceableError {
82    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
83        self.source.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
84    }
85}
86
87impl TraceableError {
88    pub fn new(message: impl Into<String>) -> Self {
89        Self {
90            message: message.into(),
91            source: None,
92        }
93    }
94
95    pub fn with_source(message: impl Into<String>, source: impl std::error::Error + Send + Sync + 'static) -> Self {
96        Self {
97            message: message.into(),
98            source: Some(Box::new(source)),
99        }
100    }
101}