common_error/
lib.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// 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
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![feature(error_iter)]
16
17pub mod ext;
18pub mod mock;
19pub mod status_code;
20
21use http::{HeaderMap, HeaderValue};
22pub use snafu;
23
24// HACK - these headers are here for shared in gRPC services. For common HTTP headers,
25// please define in `src/servers/src/http/header.rs`.
26pub const GREPTIME_DB_HEADER_ERROR_CODE: &str = "x-greptime-err-code";
27pub const GREPTIME_DB_HEADER_ERROR_MSG: &str = "x-greptime-err-msg";
28
29/// Create a http header map from error code and message.
30/// using `GREPTIME_DB_HEADER_ERROR_CODE` and `GREPTIME_DB_HEADER_ERROR_MSG` as keys.
31pub fn from_err_code_msg_to_header(code: u32, msg: &str) -> HeaderMap {
32    let mut header = HeaderMap::new();
33
34    let msg = HeaderValue::from_str(msg).unwrap_or_else(|_| {
35        HeaderValue::from_bytes(
36            &msg.as_bytes()
37                .iter()
38                .flat_map(|b| std::ascii::escape_default(*b))
39                .collect::<Vec<u8>>(),
40        )
41        .expect("Already escaped string should be valid ascii")
42    });
43
44    header.insert(GREPTIME_DB_HEADER_ERROR_CODE, code.into());
45    header.insert(GREPTIME_DB_HEADER_ERROR_MSG, msg);
46    header
47}