use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DocsError {
#[error("unsupported format: {0}")]
UnsupportedFormat(String),
#[error("macro-enabled documents are refused ({0})")]
MacroEnabled(String),
#[error("the document is encrypted")]
Encrypted,
#[error("input is {actual} bytes, over the {limit} byte limit")]
TooLarge { limit: u64, actual: u64 },
#[error("archive limit exceeded: {0}")]
ArchiveLimit(String),
#[error("malformed document: {0}")]
Malformed(String),
#[error("forbidden XML construct in {part}: {what}")]
ForbiddenXml { part: String, what: &'static str },
#[error("the target changed since it was read")]
SourceChanged,
#[error("the target already exists")]
TargetExists,
#[error("the target does not exist")]
TargetMissing,
#[error("{kind} not found: {name}")]
NotFound { kind: &'static str, name: String },
#[error("invalid operation: {0}")]
InvalidOp(String),
#[error("formula refused: {0}")]
UnsafeFormula(String),
#[error("{op} does not apply to a {format} document")]
WrongFormat {
op: &'static str,
format: &'static str,
},
#[error("pdf: {0}")]
Pdf(#[from] rightkit_pdf::model::PdfEditError),
#[error("pdf text extraction failed: {0}")]
PdfExtract(String),
#[error("i/o: {0}")]
Io(String),
#[error("saved, but a step after the replacement failed: {0}")]
SavedWithWarning(String),
}
impl DocsError {
pub fn code(&self) -> &'static str {
match self {
DocsError::UnsupportedFormat(_) => "unsupported_format",
DocsError::MacroEnabled(_) => "macro_enabled",
DocsError::Encrypted => "encrypted",
DocsError::TooLarge { .. } => "too_large",
DocsError::ArchiveLimit(_) => "archive_limit",
DocsError::Malformed(_) => "malformed",
DocsError::ForbiddenXml { .. } => "forbidden_xml",
DocsError::SourceChanged => "source_changed",
DocsError::TargetExists => "target_exists",
DocsError::TargetMissing => "target_missing",
DocsError::NotFound { .. } => "not_found",
DocsError::InvalidOp(_) => "invalid_op",
DocsError::UnsafeFormula(_) => "unsafe_formula",
DocsError::WrongFormat { .. } => "wrong_format",
DocsError::Pdf(rightkit_pdf::model::PdfEditError::EncryptedDocument) => "encrypted",
DocsError::Pdf(_) => "pdf_edit_failed",
DocsError::PdfExtract(_) => "pdf_extract_failed",
DocsError::Io(_) => "io",
DocsError::SavedWithWarning(_) => "saved_with_warning",
}
}
}
impl Serialize for DocsError {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
let mut state = serializer.serialize_struct("DocsError", 2)?;
state.serialize_field("code", self.code())?;
state.serialize_field("message", &self.to_string())?;
state.end()
}
}
pub type Result<T> = std::result::Result<T, DocsError>;