forked from apache/horaedb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherror.rs
93 lines (79 loc) · 2.93 KB
/
error.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2023 CeresDB Project Authors. Licensed under Apache-2.0.
use ceresdbproto::common::ResponseHeader;
use common_util::{define_result, error::GenericError};
use http::StatusCode;
use snafu::{Backtrace, Snafu};
use crate::error_util;
define_result!(Error);
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
pub enum Error {
#[snafu(display("Internal error, msg:{}, err:{}", msg, source))]
Internal { msg: String, source: GenericError },
#[snafu(display("Internal error, msg:{}.\nBacktrace:\n{}", msg, backtrace))]
InternalNoCause { msg: String, backtrace: Backtrace },
#[snafu(display("Rpc error, code:{:?}, err:{}", code, msg))]
ErrNoCause { code: StatusCode, msg: String },
#[snafu(display("Rpc error, code:{:?}, message:{}, err:{}", code, msg, source))]
ErrWithCause {
code: StatusCode,
msg: String,
source: GenericError,
},
#[snafu(display("sql query error, message:{}", msg))]
SqlQueryOverTTL { code: StatusCode, msg: String },
}
impl Error {
pub fn code(&self) -> StatusCode {
match *self {
Error::ErrNoCause { code, .. } => code,
Error::ErrWithCause { code, .. } => code,
Error::SqlQueryOverTTL { code, .. } => code,
Error::Internal { .. } | Error::InternalNoCause { .. } => {
StatusCode::INTERNAL_SERVER_ERROR
}
}
}
/// Get the error message returned to the user.
pub fn error_message(&self) -> String {
match self {
Error::ErrNoCause { msg, .. } | Error::InternalNoCause { msg, .. } => msg.clone(),
Error::ErrWithCause { msg, source, .. } | Error::Internal { msg, source, .. } => {
let err_string = source.to_string();
let first_line = error_util::remove_backtrace_from_err(&err_string);
format!("{msg}. Caused by: {first_line}")
}
Error::SqlQueryOverTTL { code: _, msg } => msg.clone(),
}
}
}
pub fn build_err_header(err: Error) -> ResponseHeader {
ResponseHeader {
code: err.code().as_u16() as u32,
error: err.error_message(),
}
}
pub fn build_ok_header() -> ResponseHeader {
ResponseHeader {
code: StatusCode::OK.as_u16() as u32,
..Default::default()
}
}
impl From<router::Error> for Error {
fn from(route_err: router::Error) -> Self {
match &route_err {
router::Error::RouteNotFound { .. } | router::Error::ShardNotFound { .. } => {
Error::ErrNoCause {
code: StatusCode::NOT_FOUND,
msg: route_err.to_string(),
}
}
router::Error::ParseEndpoint { .. }
| router::Error::OtherWithCause { .. }
| router::Error::OtherNoCause { .. } => Error::ErrNoCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: route_err.to_string(),
},
}
}
}