mochow_sdk_rust/mochow/api/
common.rs

1/*
2 * Copyright 2024 Baidu, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
11 * either express or implied. See the License for the specific language governing permissions
12 * and limitations under the License.
13 */
14
15use serde::Deserialize;
16use std::{error::Error, fmt::Display};
17
18use super::ServerErrorCode;
19
20/// CommonResponse, usually used as the response of a request for update info
21#[derive(Debug, Clone, Deserialize)]
22pub struct CommonResponse {
23    /// 0: success, other: error
24    pub code: i32,
25    /// success or other error message
26    pub msg: String,
27}
28
29impl Display for CommonResponse {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        write!(f, "code: {},  msg: {}", self.code, self.msg)
32    }
33}
34
35/// ServiceError, internal error of database service
36#[derive(Debug, Clone)]
37pub struct ServiceError {
38    /// http status code, like 404
39    pub status_code: i32,
40    pub request_id: String,
41    /// the detail error message
42    pub resp: CommonResponse,
43    pub server_code: ServerErrorCode,
44}
45
46impl Error for ServiceError {}
47
48impl Display for ServiceError {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(
51            f,
52            "status_code: {}, request_id: {}, msg: {:?}, server_code: {:?}",
53            self.status_code, self.request_id, self.resp, self.server_code,
54        )
55    }
56}
57
58#[cfg(test)]
59mod tests {
60
61    use crate::mochow::api::{CommonResponse, ServerErrorCode};
62
63    use super::ServiceError;
64
65    #[test]
66    fn test_service_err() {
67        let err = ServiceError {
68            status_code: -1,
69            request_id: "12234".to_string(),
70            resp: CommonResponse {
71                code: 123,
72                msg: "test".to_string(),
73            },
74            server_code: ServerErrorCode::UNKNOWN,
75        };
76        println!("{}", err)
77    }
78}