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.
1718use bytes::Buf;
19use http::Response;
20use serde::Deserialize;
2122use crate::raw::*;
23use crate::*;
2425/// the error response of seafile
26#[derive(Default, Debug, Deserialize)]
27#[allow(dead_code)]
28struct SeafileError {
29 error_msg: String,
30}
3132/// Parse error response into Error.
33pub(super) fn parse_error(resp: Response<Buffer>) -> Error {
34let (parts, body) = resp.into_parts();
35let bs = body.to_bytes();
3637let (kind, _retryable) = match parts.status.as_u16() {
38403 => (ErrorKind::PermissionDenied, false),
39404 => (ErrorKind::NotFound, false),
40520 => (ErrorKind::Unexpected, false),
41_ => (ErrorKind::Unexpected, false),
42 };
4344let (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));
4748let mut err = Error::new(kind, message);
4950 err = with_error_response_context(err, parts);
5152 err
53}
5455#[cfg(test)]
56mod test {
57use http::StatusCode;
5859use super::*;
6061#[tokio::test]
62async fn test_parse_error() {
63let err_res = vec![
64 (
65r#"{"error_msg": "Permission denied"}"#,
66 ErrorKind::PermissionDenied,
67 StatusCode::FORBIDDEN,
68 ),
69 (
70r#"{"error_msg": "Folder /e982e75a-fead-487c-9f41-63094d9bf0de/a9d867b9-778d-4612-b674-47e674c14c28/ not found."}"#,
71 ErrorKind::NotFound,
72 StatusCode::NOT_FOUND,
73 ),
74 ];
7576for res in err_res {
77let bs = bytes::Bytes::from(res.0);
78let body = Buffer::from(bs);
79let resp = Response::builder().status(res.2).body(body).unwrap();
8081let err = parse_error(resp);
8283assert_eq!(err.kind(), res.1);
84 }
85 }
86}