Skip to main content

cdk_ffi/
error.rs

1//! FFI Error types
2
3use cdk::Error as CdkError;
4use cdk_common::error::ErrorResponse;
5
6/// FFI Error type that wraps CDK errors for cross-language use
7///
8/// This simplified error type uses protocol-compliant error codes from `ErrorCode`
9/// in `cdk-common`, reducing duplication while providing structured error information
10/// to FFI consumers.
11#[derive(Debug, thiserror::Error, uniffi::Error)]
12pub enum FfiError {
13    /// CDK error with protocol-compliant error code
14    /// The code corresponds to the Cashu protocol error codes (e.g., 11001, 20001, etc.)
15    #[error("[{code}] {error_message}")]
16    Cdk {
17        /// Error code from the Cashu protocol specification
18        code: u32,
19        /// Human-readable error message
20        error_message: String,
21    },
22
23    /// Internal/infrastructure error (no protocol error code)
24    /// Used for errors that don't map to Cashu protocol codes
25    #[error("{error_message}")]
26    Internal {
27        /// Human-readable error message
28        error_message: String,
29    },
30}
31
32impl FfiError {
33    /// Create an internal error from any type that implements ToString
34    pub fn internal(msg: impl ToString) -> Self {
35        FfiError::Internal {
36            error_message: msg.to_string(),
37        }
38    }
39
40    /// Create a database error (uses Unknown code 50000)
41    pub fn database(msg: impl ToString) -> Self {
42        FfiError::Cdk {
43            code: 50000,
44            error_message: msg.to_string(),
45        }
46    }
47}
48
49impl From<CdkError> for FfiError {
50    fn from(err: CdkError) -> Self {
51        let response = ErrorResponse::from(err);
52        FfiError::Cdk {
53            code: response.code.to_code() as u32,
54            error_message: response.detail,
55        }
56    }
57}
58
59impl From<cdk::amount::Error> for FfiError {
60    fn from(err: cdk::amount::Error) -> Self {
61        FfiError::internal(err)
62    }
63}
64
65impl From<cdk::nuts::nut00::Error> for FfiError {
66    fn from(err: cdk::nuts::nut00::Error) -> Self {
67        FfiError::internal(err)
68    }
69}
70
71impl From<serde_json::Error> for FfiError {
72    fn from(err: serde_json::Error) -> Self {
73        FfiError::internal(err)
74    }
75}