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: Vec<u8>,
18 },
19 #[error("{0}")]
20 ApiError(ApiError),
21 #[error("invalid argument:{0}")]
22 InvalidArgument(String),
23 #[error("stream error:{0}")]
24 StreamError(String),
25 #[error("response body contains invalid UTF-8: {0}")]
26 InvalidUtf8(#[from] std::string::FromUtf8Error),
27}
28
29#[derive(Debug, Deserialize, Clone)]
30pub struct ApiError {
31 pub message: String,
32 pub request_id: Option<String>,
33 pub code: Option<String>,
34}
35
36impl Display for ApiError {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 let mut parts = Vec::new();
39 if let Some(code) = &self.code {
40 parts.push(format!("code: {code}"));
41 }
42 if let Some(request_id) = &self.request_id {
43 parts.push(format!("request_id: {request_id}"));
44 }
45 write!(f, "{}", parts.join(" "))
46 }
47}
48
49impl From<crate::operation::common::ParametersBuilderError> for DashScopeError {
50 fn from(error: crate::operation::common::ParametersBuilderError) -> Self {
51 DashScopeError::InvalidArgument(error.to_string())
52 }
53}
54
55pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> DashScopeError {
56 tracing::error!(
57 "failed deserialization of: {}",
58 String::from_utf8_lossy(bytes)
59 );
60 DashScopeError::JSONDeserialize {
61 source: e,
62 raw_response: bytes.to_vec(),
63 }
64}
65
66pub type Result<T> = std::result::Result<T, DashScopeError>;