use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::Binary;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SystemError {
InvalidRequest {
error: String,
request: Binary,
},
InvalidResponse {
error: String,
response: Binary,
},
NoSuchContract {
addr: String,
},
NoSuchCode {
code_id: u64,
},
Unknown {},
UnsupportedRequest {
kind: String,
},
}
impl std::error::Error for SystemError {}
impl core::fmt::Display for SystemError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
SystemError::InvalidRequest { error, request } => write!(
f,
"Cannot parse request: {} in: {}",
error,
String::from_utf8_lossy(request)
),
SystemError::InvalidResponse { error, response } => write!(
f,
"Cannot parse response: {} in: {}",
error,
String::from_utf8_lossy(response)
),
SystemError::NoSuchContract { addr } => write!(f, "No such contract: {addr}"),
SystemError::NoSuchCode { code_id } => write!(f, "No such code: {code_id}"),
SystemError::Unknown {} => write!(f, "Unknown system error"),
SystemError::UnsupportedRequest { kind } => {
write!(f, "Unsupported query type: {kind}")
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{from_json, to_json_vec};
#[test]
fn system_error_no_such_contract_serialization() {
let err = SystemError::NoSuchContract {
addr: "gibtsnicht".to_string(),
};
let json = to_json_vec(&err).unwrap();
assert_eq!(
String::from_utf8_lossy(&json),
r#"{"no_such_contract":{"addr":"gibtsnicht"}}"#,
);
let err: SystemError = from_json(br#"{"no_such_contract":{"addr":"nada"}}"#).unwrap();
assert_eq!(
err,
SystemError::NoSuchContract {
addr: "nada".to_string()
}
);
}
#[test]
fn system_error_no_such_code_serialization() {
let err = SystemError::NoSuchCode { code_id: 13 };
let json = to_json_vec(&err).unwrap();
assert_eq!(
String::from_utf8_lossy(&json),
r#"{"no_such_code":{"code_id":13}}"#,
);
let err: SystemError = from_json(br#"{"no_such_code":{"code_id":987}}"#).unwrap();
assert_eq!(err, SystemError::NoSuchCode { code_id: 987 },);
}
}