opendal/services/vercel_blob/
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 quick_xml::de;
21use serde::Deserialize;
22
23use crate::raw::*;
24use crate::*;
25
26/// VercelBlobError is the error returned by VercelBlob service.
27#[derive(Default, Debug, Deserialize)]
28#[serde(default)]
29struct VercelBlobError {
30    error: VercelBlobErrorDetail,
31}
32
33#[derive(Default, Debug, Deserialize)]
34#[serde(default)]
35struct VercelBlobErrorDetail {
36    code: String,
37    message: Option<String>,
38}
39
40/// Parse error response into Error.
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.as_u16() {
46        403 => (ErrorKind::PermissionDenied, false),
47        404 => (ErrorKind::NotFound, false),
48        500 | 502 | 503 | 504 => (ErrorKind::Unexpected, true),
49        _ => (ErrorKind::Unexpected, false),
50    };
51
52    let (message, _vercel_blob_err) = de::from_reader::<_, VercelBlobError>(bs.clone().reader())
53        .map(|vercel_blob_err| (format!("{vercel_blob_err:?}"), Some(vercel_blob_err)))
54        .unwrap_or_else(|_| (String::from_utf8_lossy(&bs).into_owned(), None));
55
56    let mut err = Error::new(kind, message);
57
58    err = with_error_response_context(err, parts);
59
60    if retryable {
61        err = err.set_temporary();
62    }
63
64    err
65}
66
67#[cfg(test)]
68mod test {
69    use http::StatusCode;
70
71    use super::*;
72
73    #[tokio::test]
74    async fn test_parse_error() {
75        let err_res = vec![(
76            r#"{
77                    "error": {
78                        "code": "forbidden",
79                        "message": "Invalid token"
80                    }
81                }"#,
82            ErrorKind::PermissionDenied,
83            StatusCode::FORBIDDEN,
84        )];
85
86        for res in err_res {
87            let body = Buffer::from(res.0.as_bytes().to_vec());
88            let resp = Response::builder().status(res.2).body(body).unwrap();
89
90            let err = parse_error(resp);
91
92            assert_eq!(err.kind(), res.1);
93        }
94
95        let bs = bytes::Bytes::from(
96            r#"{
97                "error": {
98                    "code": "forbidden",
99                    "message": "Invalid token"
100                }
101            }"#,
102        );
103
104        let out: VercelBlobError = serde_json::from_reader(bs.reader()).expect("must success");
105        println!("{out:?}");
106
107        assert_eq!(out.error.code, "forbidden");
108        assert_eq!(out.error.message, Some("Invalid token".to_string()));
109    }
110}