use std::path::PathBuf;
use crate::parser::crypto::CryptoError;
use crate::parser::{FileFormat, ParseError};
use crate::HwpError;
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceError {
NotFound {
path: PathBuf,
},
Io {
path: PathBuf,
kind: std::io::ErrorKind,
},
UnsupportedFormat {
detected: FileFormat,
},
PasswordRequired,
PasswordMismatch,
TooLarge {
size_bytes: usize,
limit_bytes: usize,
},
Parse(String),
}
impl ServiceError {
pub fn code(&self) -> &'static str {
match self {
ServiceError::NotFound { .. } => "NOT_FOUND",
ServiceError::Io { .. } => "IO",
ServiceError::UnsupportedFormat { .. } => "UNSUPPORTED_FORMAT",
ServiceError::PasswordRequired => "PASSWORD_REQUIRED",
ServiceError::PasswordMismatch => "PASSWORD_MISMATCH",
ServiceError::TooLarge { .. } => "TOO_LARGE",
ServiceError::Parse(_) => "PARSE",
}
}
pub fn is_usage_error(&self) -> bool {
matches!(
self,
ServiceError::NotFound { .. }
| ServiceError::UnsupportedFormat { .. }
| ServiceError::PasswordRequired
| ServiceError::TooLarge { .. }
)
}
pub fn needs_password(&self) -> bool {
matches!(
self,
ServiceError::PasswordRequired | ServiceError::PasswordMismatch
)
}
pub(crate) fn from_open_failure(error: &HwpError, password_supplied: bool) -> ServiceError {
let HwpError::InvalidFile(inner) = error else {
return ServiceError::Parse(error.to_string());
};
if inner.contains(&CryptoError::WrongPassword.to_string()) {
return ServiceError::PasswordMismatch;
}
if inner.contains(&ParseError::EncryptedDocument.to_string()) {
return if password_supplied {
ServiceError::PasswordMismatch
} else {
ServiceError::PasswordRequired
};
}
ServiceError::Parse(inner.clone())
}
}
impl std::fmt::Display for ServiceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ServiceError::NotFound { path } => {
write!(f, "파일을 찾을 수 없습니다: {}", path.display())
}
ServiceError::Io { path, kind } => {
write!(f, "파일을 읽을 수 없습니다: {} ({kind:?})", path.display())
}
ServiceError::UnsupportedFormat { detected } => match detected {
FileFormat::Pdf => write!(f, "PDF_IMPORT_DISABLED: {}", crate::parser::PDF_IMPORT_DISABLED_HINT),
FileFormat::Empty => write!(f, "빈 파일(0 바이트)입니다."),
FileFormat::DrmProtected => write!(
f,
"DRM/보안 컨테이너로 보호된 문서입니다. 보호를 해제한 뒤 저장해 열어주세요."
),
other => write!(
f,
"지원하지 않는 형식입니다: {other:?}. rhwp 는 HWP 5.0·HWPX·일부 HWP 3.0·HWPML 을 엽니다."
),
},
ServiceError::PasswordRequired => {
write!(f, "비밀번호가 필요한 암호 문서입니다.")
}
ServiceError::PasswordMismatch => write!(
f,
"비밀번호가 일치하지 않거나 암호화 데이터가 손상되었습니다."
),
ServiceError::TooLarge {
size_bytes,
limit_bytes,
} => write!(
f,
"입력이 크기 상한을 넘었습니다: {size_bytes}바이트 (상한 {limit_bytes}바이트)"
),
ServiceError::Parse(message) => write!(f, "문서 파싱 실패 - {message}"),
}
}
}
impl std::error::Error for ServiceError {}