opendal/services/seafile/
error.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use bytes::Buf;
19use http::Response;
20use serde::Deserialize;
21
22use crate::raw::*;
23use crate::*;
24
25/// the error response of seafile
26#[derive(Default, Debug, Deserialize)]
27#[allow(dead_code)]
28struct SeafileError {
29    error_msg: String,
30}
31
32/// Parse error response into Error.
33pub(super) fn parse_error(resp: Response<Buffer>) -> Error {
34    let (parts, body) = resp.into_parts();
35    let bs = body.to_bytes();
36
37    let (kind, _retryable) = match parts.status.as_u16() {
38        403 => (ErrorKind::PermissionDenied, false),
39        404 => (ErrorKind::NotFound, false),
40        520 => (ErrorKind::Unexpected, false),
41        _ => (ErrorKind::Unexpected, false),
42    };
43
44    let (message, _seafile_err) = serde_json::from_reader::<_, SeafileError>(bs.clone().reader())
45        .map(|seafile_err| (format!("{seafile_err:?}"), Some(seafile_err)))
46        .unwrap_or_else(|_| (String::from_utf8_lossy(&bs).into_owned(), None));
47
48    let mut err = Error::new(kind, message);
49
50    err = with_error_response_context(err, parts);
51
52    err
53}
54
55#[cfg(test)]
56mod test {
57    use http::StatusCode;
58
59    use super::*;
60
61    #[tokio::test]
62    async fn test_parse_error() {
63        let err_res = vec![
64            (
65                r#"{"error_msg": "Permission denied"}"#,
66                ErrorKind::PermissionDenied,
67                StatusCode::FORBIDDEN,
68            ),
69            (
70                r#"{"error_msg": "Folder /e982e75a-fead-487c-9f41-63094d9bf0de/a9d867b9-778d-4612-b674-47e674c14c28/ not found."}"#,
71                ErrorKind::NotFound,
72                StatusCode::NOT_FOUND,
73            ),
74        ];
75
76        for res in err_res {
77            let bs = bytes::Bytes::from(res.0);
78            let body = Buffer::from(bs);
79            let resp = Response::builder().status(res.2).body(body).unwrap();
80
81            let err = parse_error(resp);
82
83            assert_eq!(err.kind(), res.1);
84        }
85    }
86}