opendal_core/services/dbfs/
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 std::fmt::Debug;
19
20use http::Response;
21use http::StatusCode;
22use serde::Deserialize;
23
24use crate::raw::*;
25use crate::*;
26
27/// DbfsError is the error returned by DBFS service.
28#[derive(Default, Deserialize)]
29struct DbfsError {
30    error_code: String,
31    message: String,
32}
33
34impl Debug for DbfsError {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("DbfsError")
37            .field("error_code", &self.error_code)
38            // replace `\n` to ` ` for better reading.
39            .field("message", &self.message.replace('\n', " "))
40            .finish()
41    }
42}
43
44pub(super) fn parse_error(resp: Response<Buffer>) -> Error {
45    let (parts, body) = resp.into_parts();
46    let bs = body.to_bytes();
47
48    let (kind, retryable) = match parts.status {
49        StatusCode::NOT_FOUND => (ErrorKind::NotFound, false),
50        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => (ErrorKind::PermissionDenied, false),
51        StatusCode::PRECONDITION_FAILED => (ErrorKind::ConditionNotMatch, false),
52        StatusCode::INTERNAL_SERVER_ERROR
53        | StatusCode::BAD_GATEWAY
54        | StatusCode::SERVICE_UNAVAILABLE
55        | StatusCode::GATEWAY_TIMEOUT => (ErrorKind::Unexpected, true),
56        _ => (ErrorKind::Unexpected, false),
57    };
58
59    let message = match serde_json::from_slice::<DbfsError>(&bs) {
60        Ok(dbfs_error) => format!("{:?}", dbfs_error.message),
61        Err(_) => String::from_utf8_lossy(&bs).into_owned(),
62    };
63
64    let mut err = Error::new(kind, message);
65
66    err = with_error_response_context(err, parts);
67
68    if retryable {
69        err = err.set_temporary();
70    }
71
72    err
73}