async_dashscope/
error.rs

1use std::fmt::Display;
2
3use reqwest_eventsource::CannotCloneRequestError;
4use serde::Deserialize;
5
6#[derive(Debug, thiserror::Error)]
7pub enum DashScopeError {
8    #[error("http error: {0}")]
9    Reqwest(#[from] reqwest::Error),
10
11    #[error("event source error: {0}")]
12    EventSource(#[from] CannotCloneRequestError),
13
14    #[error("failed to deserialize api response: {source}")]
15    JSONDeserialize {
16        source: serde_json::Error,
17        raw_response:String,
18    },
19    #[error("serialization error: {0}")]
20    SerializationError(String),
21    #[error("{0}")]
22    ElementError(String),
23    #[error("{0}")]
24    ApiError(ApiError),
25    #[error("invalid argument:{0}")]
26    InvalidArgument(String),
27    #[error("stream error:{0}")]
28    StreamError(String),
29    #[error("response body contains invalid UTF-8: {0}")]
30    InvalidUtf8(#[from] std::string::FromUtf8Error),
31
32    #[error("upload error: {0}")]
33    UploadError(String),
34    
35    #[error("timeout error: {0}")]
36    TimeoutError(String),
37    #[cfg(feature = "websocket")]
38    #[error("websocket error: {0}")]
39    WebSocketError(#[from] reqwest_websocket::Error),
40
41    #[error("unknown event type: {event_type}")]
42    UnknownEventType{
43        event_type: String,
44    }
45}
46
47#[derive(Debug, Deserialize, Clone)]
48pub struct ApiError {
49    pub message: String,
50    pub request_id: Option<String>,
51    pub code: Option<String>,
52}
53
54impl Display for ApiError {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        let mut parts = Vec::new();
57        if let Some(code) = &self.code {
58            parts.push(format!("code: {code}"));
59        }
60        if let Some(request_id) = &self.request_id {
61            parts.push(format!("request_id: {request_id}"));
62        }
63        write!(f, "{}", parts.join(" "))
64    }
65}
66
67impl From<crate::operation::common::ParametersBuilderError> for DashScopeError {
68    fn from(error: crate::operation::common::ParametersBuilderError) -> Self {
69        DashScopeError::InvalidArgument(error.to_string())
70    }
71}
72
73pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> DashScopeError {
74    tracing::error!(
75        "failed deserialization of: {}",
76        String::from_utf8_lossy(bytes)
77    );
78    DashScopeError::JSONDeserialize {
79        source: e,
80        raw_response: String::from_utf8_lossy(bytes).to_string(),
81    }
82}
83
84pub type Result<T> = std::result::Result<T, DashScopeError>;