soundcloud_rs/models/
error.rs

1use std::fmt;
2
3/// Error type for SoundCloud API operations
4#[derive(Debug)]
5pub struct Error {
6    message: String,
7    source: Option<Box<dyn std::error::Error + Send + Sync>>,
8}
9
10impl Error {
11    /// Create a new error from a message
12    pub fn new(msg: impl Into<String>) -> Self {
13        Self {
14            message: msg.into(),
15            source: None,
16        }
17    }
18
19    /// Create an error from another error with a message
20    pub fn from_error<E: std::error::Error + Send + Sync + 'static>(msg: impl Into<String>, source: E) -> Self {
21        Self {
22            message: msg.into(),
23            source: Some(Box::new(source)),
24        }
25    }
26}
27
28// REQUIRED: std::error::Error requires Display to be implemented
29impl fmt::Display for Error {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        write!(f, "{}", self.message)
32    }
33}
34
35// REQUIRED: Makes Error usable in Result<T, E>
36// OPTIONAL: source() method - we implement it to expose underlying errors for debugging
37impl std::error::Error for Error {
38    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
39        self.source.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
40    }
41}
42
43// OPTIONAL but CONVENIENT: Allows automatic conversion via ? operator
44// Without these, you'd need: .map_err(|e| Error::new(format!("...")))? everywhere
45impl From<reqwest::Error> for Error {
46    fn from(err: reqwest::Error) -> Self {
47        Self::from_error("HTTP request failed", err)
48    }
49}
50
51impl From<serde_json::Error> for Error {
52    fn from(err: serde_json::Error) -> Self {
53        Self::from_error("JSON parsing failed", err)
54    }
55}
56
57impl From<std::io::Error> for Error {
58    fn from(err: std::io::Error) -> Self {
59        Self::from_error("IO operation failed", err)
60    }
61}
62
63// OPTIONAL: Convenience for creating errors from strings
64impl From<&str> for Error {
65    fn from(msg: &str) -> Self {
66        Self::new(msg)
67    }
68}
69
70impl From<String> for Error {
71    fn from(msg: String) -> Self {
72        Self::new(msg)
73    }
74}
75