error.rs 2.1 KB

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