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