use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ErrorOutput {
pub error: bool,
pub message: String,
pub exit_code: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub help: Option<String>,
}
impl ErrorOutput {
#[must_use]
pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
Self {
error: true,
message: message.into(),
exit_code,
code: None,
help: None,
}
}
#[must_use]
pub fn with_code(mut self, code: Option<String>) -> Self {
self.code = code;
self
}
#[must_use]
pub fn with_help(mut self, help: Option<String>) -> Self {
self.help = help;
self
}
}
#[cfg(test)]
mod tests {
use super::ErrorOutput;
#[test]
fn absent_code_and_help_add_no_keys() {
let json = serde_json::to_value(ErrorOutput::new("boom", 2)).expect("serializes");
let object = json.as_object().expect("object");
assert_eq!(object.len(), 3, "{json}");
assert!(!object.contains_key("code"));
assert!(!object.contains_key("help"));
}
#[test]
fn code_and_help_reach_the_wire_when_present() {
let json = serde_json::to_value(
ErrorOutput::new("boom", 2)
.with_code(Some("FALLOW_BOOM".to_owned()))
.with_help(Some("try harder".to_owned())),
)
.expect("serializes");
assert_eq!(json["code"], "FALLOW_BOOM");
assert_eq!(json["help"], "try harder");
}
}