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
use ciphercore_utils::errors::{CiphercoreErrorBody, ErrorWithBody};
use json::JsonError;
use ndarray::ShapeError;
use std::num::ParseIntError;
use serde::{Deserialize, Serialize};
use std::fmt;
#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct CiphercoreBaseError {
body: CiphercoreErrorBody,
}
impl CiphercoreBaseError {
pub fn new(body: CiphercoreErrorBody) -> Self {
Self { body }
}
}
impl ErrorWithBody for CiphercoreBaseError {
fn get_body(&self) -> CiphercoreErrorBody {
self.body.clone()
}
}
impl fmt::Display for CiphercoreBaseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", serde_json::to_string_pretty(&self).unwrap())
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! runtime_error {
($($x:tt)*) => {
$crate::errors::CiphercoreBaseError::new(ciphercore_utils::runtime_error_body!($($x)*))
};
}
impl From<ParseIntError> for CiphercoreBaseError {
fn from(err: ParseIntError) -> CiphercoreBaseError {
runtime_error!("ParseIntError: {}", err)
}
}
impl From<serde_json::Error> for CiphercoreBaseError {
fn from(err: serde_json::Error) -> CiphercoreBaseError {
let err_str = err.to_string();
serde_json::from_str::<CiphercoreBaseError>(&err_str)
.expect("Error during error conversion form serde_json error to CiphercoreBaseError")
}
}
impl From<std::io::Error> for CiphercoreBaseError {
fn from(err: std::io::Error) -> CiphercoreBaseError {
runtime_error!("std::io::Error: {}", err)
}
}
impl From<ShapeError> for CiphercoreBaseError {
fn from(err: ShapeError) -> CiphercoreBaseError {
runtime_error!("NDArray shape error: {}", err)
}
}
impl From<JsonError> for CiphercoreBaseError {
fn from(err: JsonError) -> CiphercoreBaseError {
runtime_error!("JSON error: {}", err)
}
}
impl From<std::ffi::NulError> for CiphercoreBaseError {
fn from(err: std::ffi::NulError) -> CiphercoreBaseError {
runtime_error!("Null error: {}", err)
}
}
impl From<std::str::Utf8Error> for CiphercoreBaseError {
fn from(err: std::str::Utf8Error) -> CiphercoreBaseError {
runtime_error!("Utf8Error: {}", err)
}
}
pub type Result<T> = std::result::Result<T, CiphercoreBaseError>;
#[cfg(test)]
mod tests {
use crate::errors::CiphercoreBaseError;
use serde_json::Value;
#[test]
fn test_serialization_error_conversion() {
let orignal_error = runtime_error!("Value version doesn't match the requirement");
let orignal_error_str = orignal_error.to_string();
let serde_error: Result<Value, serde_json::Error> =
Err(orignal_error).map_err(serde::de::Error::custom);
if let Err(e) = serde_error {
let cipher_err = CiphercoreBaseError::from(e);
assert_eq!(orignal_error_str, cipher_err.to_string());
}
}
}