-
Notifications
You must be signed in to change notification settings - Fork 763
/
Copy pathexception.rs
312 lines (278 loc) · 7.98 KB
/
exception.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
#![allow(non_snake_case)]
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::sync::Arc;
use backtrace::Backtrace;
use thiserror::Error;
#[derive(Clone)]
pub enum ErrorCodesBacktrace {
Serialized(Arc<String>),
Origin(Arc<Backtrace>),
}
impl ToString for ErrorCodesBacktrace {
fn to_string(&self) -> String {
match self {
ErrorCodesBacktrace::Serialized(backtrace) => Arc::as_ref(backtrace).clone(),
ErrorCodesBacktrace::Origin(backtrace) => {
format!("{:?}", backtrace)
}
}
}
}
#[derive(Error)]
pub struct ErrorCodes {
code: u16,
display_text: String,
// cause is only used to contain an `anyhow::Error`.
// TODO: remove `cause` when we completely get rid of `anyhow::Error`.
cause: Option<Box<dyn std::error::Error + Sync + Send>>,
backtrace: Option<ErrorCodesBacktrace>,
}
impl ErrorCodes {
pub fn code(&self) -> u16 {
self.code
}
pub fn message(&self) -> String {
self.cause
.as_ref()
.map(|cause| format!("{:?}", cause))
.unwrap_or_else(|| self.display_text.clone())
}
pub fn backtrace(&self) -> Option<ErrorCodesBacktrace> {
self.backtrace.clone()
}
pub fn backtrace_str(&self) -> String {
match self.backtrace.as_ref() {
None => "".to_string(),
Some(backtrace) => backtrace.to_string(),
}
}
}
macro_rules! as_item {
($i:item) => {
$i
};
}
macro_rules! build_exceptions {
($($body:tt($code:expr)),*) => {
as_item! {
impl ErrorCodes {
$(
pub fn $body(display_text: impl Into<String>) -> ErrorCodes {
ErrorCodes {
code:$code,
display_text: display_text.into(),
cause: None,
backtrace: Some(ErrorCodesBacktrace::Origin(Arc::new(Backtrace::new()))),
}
})*
}
}
}
}
build_exceptions! {
Ok(0),
UnknownTypeOfQuery(1),
UnImplement(2),
UnknownDatabase(3),
UnknownSetting(4),
SyntaxException(5),
BadArguments(6),
IllegalDataType(7),
UnknownFunction(8),
IllegalFunctionState(9),
BadDataValueType(10),
UnknownPlan(11),
IllegalPipelineState(12),
BadTransformType(13),
IllegalTransformConnectionState(14),
LogicalError(15),
EmptyData(16),
DataStructMissMatch(17),
BadDataArrayLength(18),
UnknownContextID(19),
UnknownVariable(20),
UnknownTableFunction(21),
BadOption(22),
CannotReadFile(23),
ParquetError(24),
UnknownTable(25),
IllegalAggregateExp(26),
UnknownAggregateFunction(27),
NumberArgumentsNotMatch(28),
NotFoundStream(29),
EmptyDataFromServer(30),
NotFoundLocalNode(31),
PlanScheduleError(32),
BadPlanInputs(33),
DuplicateClusterNode(34),
NotFoundClusterNode(35),
BadAddressFormat(36),
DnsParseError(37),
CannotConnectNode(38),
DuplicateGetStream(39),
UnknownException(1000),
TokioError(1001)
}
// Store errors
build_exceptions! {
FileMetaNotFound(2001),
FileDamaged(2002)
}
pub type Result<T> = std::result::Result<T, ErrorCodes>;
impl Debug for ErrorCodes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Code: {}, displayText = {}.",
self.code(),
self.message(),
)?;
match self.backtrace.as_ref() {
None => Ok(()), // no backtrace
Some(backtrace) => {
// TODO: Custom stack frame format for print
match backtrace {
ErrorCodesBacktrace::Origin(backtrace) => write!(f, "\n\n{:?}", backtrace),
ErrorCodesBacktrace::Serialized(backtrace) => write!(f, "\n\n{:?}", backtrace),
}
}
}
}
}
impl Display for ErrorCodes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Code: {}, displayText = {}.",
self.code(),
self.message(),
)
}
}
#[derive(Error)]
enum OtherErrors {
AnyHow { error: anyhow::Error },
}
impl Display for OtherErrors {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
OtherErrors::AnyHow { error } => write!(f, "{}", error),
}
}
}
impl Debug for OtherErrors {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
OtherErrors::AnyHow { error } => write!(f, "{:?}", error),
}
}
}
impl From<anyhow::Error> for ErrorCodes {
fn from(error: anyhow::Error) -> Self {
ErrorCodes {
code: 1002,
display_text: String::from(""),
cause: Some(Box::new(OtherErrors::AnyHow { error })),
backtrace: None,
}
}
}
impl From<std::num::ParseIntError> for ErrorCodes {
fn from(error: std::num::ParseIntError) -> Self {
ErrorCodes::from_std_error(error)
}
}
impl From<std::num::ParseFloatError> for ErrorCodes {
fn from(error: std::num::ParseFloatError) -> Self {
ErrorCodes::from_std_error(error)
}
}
impl From<common_arrow::arrow::error::ArrowError> for ErrorCodes {
fn from(error: common_arrow::arrow::error::ArrowError) -> Self {
ErrorCodes::from_std_error(error)
}
}
impl From<serde_json::Error> for ErrorCodes {
fn from(error: serde_json::Error) -> Self {
ErrorCodes::from_std_error(error)
}
}
impl From<sqlparser::parser::ParserError> for ErrorCodes {
fn from(error: sqlparser::parser::ParserError) -> Self {
ErrorCodes::from_std_error(error)
}
}
impl From<std::io::Error> for ErrorCodes {
fn from(error: std::io::Error) -> Self {
ErrorCodes::from_std_error(error)
}
}
impl ErrorCodes {
pub fn from_std_error<T: std::error::Error>(error: T) -> Self {
ErrorCodes {
code: 1002,
display_text: format!("{}", error),
cause: None,
backtrace: Some(ErrorCodesBacktrace::Origin(Arc::new(Backtrace::new()))),
}
}
pub fn create(
code: u16,
display_text: String,
backtrace: Option<ErrorCodesBacktrace>,
) -> ErrorCodes {
ErrorCodes {
code,
display_text,
cause: None,
backtrace,
}
}
}
/// Provides the `map_err_to_code` method for `Result`.
///
/// ```
/// use common_exception::ToErrorCodes;
/// use common_exception::ErrorCodes;
///
/// let x: std::result::Result<(), std::fmt::Error> = Err(std::fmt::Error {});
/// let y: common_exception::Result<()> =
/// x.map_err_to_code(ErrorCodes::UnknownException, || 123);
///
/// assert_eq!(
/// "Code: 1000, displayText = 123, cause: an error occurred when formatting an argument.",
/// format!("{}", y.unwrap_err())
/// );
/// ```
pub trait ToErrorCodes<T, E, CtxFn> {
/// Wrap the error value with ErrorCodes that is evaluated lazily
/// only once an error does occur.
///
/// `err_code_fn` is one of the ErrorCodes builder function such as `ErrorCodes::Ok`.
/// `context_fn` builds display_text for the ErrorCodes.
fn map_err_to_code<ErrFn, D>(self, err_code_fn: ErrFn, context_fn: CtxFn) -> Result<T>
where
ErrFn: FnOnce(String) -> ErrorCodes,
D: Display,
CtxFn: FnOnce() -> D;
}
impl<T, E, CtxFn> ToErrorCodes<T, E, CtxFn> for std::result::Result<T, E>
where E: std::error::Error + Send + Sync + 'static
{
fn map_err_to_code<ErrFn, D>(self, make_exception: ErrFn, context_fn: CtxFn) -> Result<T>
where
ErrFn: FnOnce(String) -> ErrorCodes,
D: Display,
CtxFn: FnOnce() -> D,
{
self.map_err(|error| {
let err_text = format!("{}, cause: {}", context_fn(), error);
make_exception(err_text)
})
}
}