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