opendal_core/services/huggingface/
error.rs1use std::fmt::Debug;
19
20use http::Response;
21use http::StatusCode;
22use serde::Deserialize;
23
24use crate::raw::*;
25use crate::*;
26
27#[derive(Default, Deserialize)]
29struct HuggingfaceError {
30 error: String,
31}
32
33impl Debug for HuggingfaceError {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 f.debug_struct("HuggingfaceError")
36 .field("message", &self.error.replace('\n', " "))
37 .finish()
38 }
39}
40
41pub(super) fn parse_error(resp: Response<Buffer>) -> Error {
42 let (parts, body) = resp.into_parts();
43 let bs = body.to_bytes();
44
45 let (kind, retryable) = match parts.status {
46 StatusCode::NOT_FOUND => (ErrorKind::NotFound, false),
47 StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => (ErrorKind::PermissionDenied, false),
48 StatusCode::PRECONDITION_FAILED => (ErrorKind::ConditionNotMatch, false),
49 StatusCode::INTERNAL_SERVER_ERROR
50 | StatusCode::BAD_GATEWAY
51 | StatusCode::SERVICE_UNAVAILABLE
52 | StatusCode::GATEWAY_TIMEOUT => (ErrorKind::Unexpected, true),
53 _ => (ErrorKind::Unexpected, false),
54 };
55
56 let message = match serde_json::from_slice::<HuggingfaceError>(&bs) {
57 Ok(hf_error) => format!("{:?}", hf_error.error),
58 Err(_) => String::from_utf8_lossy(&bs).into_owned(),
59 };
60
61 let mut err = Error::new(kind, message);
62
63 err = with_error_response_context(err, parts);
64
65 if retryable {
66 err = err.set_temporary();
67 }
68
69 err
70}
71
72#[cfg(test)]
73mod test {
74 use super::*;
75 use crate::raw::new_json_deserialize_error;
76 use crate::types::Result;
77
78 #[test]
79 fn test_parse_error() -> Result<()> {
80 let resp = r#"
81 {
82 "error": "Invalid username or password."
83 }
84 "#;
85 let decoded_response = serde_json::from_slice::<HuggingfaceError>(resp.as_bytes())
86 .map_err(new_json_deserialize_error)?;
87
88 assert_eq!(decoded_response.error, "Invalid username or password.");
89
90 Ok(())
91 }
92}