第 13 节,共 25 节
错误
目录
- 每个 crate 都有自己的错误枚举(使用
thiserror)。切片可以在error.rs中有自己的错误枚举。 core返回领域错误。app/<slice>/dto.rs把切片的错误转换成供窗口使用的代码和句子键,与切片的其他线上类型放在一起。app/error.rs只保存IpcError本身,因此新切片在自己的文件夹中添加它的错误,而不是在一个共享文件中。这句话来自你的翻译表,绝不来自线上枚举的Display。- 来自线上的未知事件不是错误。 在枚举上使用
#[serde(other)],在非必需字段上使用Option<T>。把未知的行记录到调试日志,然后继续。提供商命令行工具的新版本绝不能让一次运行停止。 - 在
kit、store、drivers和core中,除测试外禁止unwrap()和panic!。使用带错误变体的?,或者带有原因说明(解释为什么该值不可能缺失)的expect()。
#[derive(Debug, thiserror::Error)]
pub enum RecordingError {
#[error("the recorder could not start")]
RecorderDidNotStart(#[source] PlatformError),
#[error("the recording folder is not writable")]
FolderNotWritable(#[source] std::io::Error),
#[error("a recording is already running")]
AlreadyRunning,
}
app/src/error.rs:
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IpcError {
code: &'static str,
message_key: &'static str,
}
impl IpcError {
pub fn new(code: &'static str, message_key: &'static str) -> Self {
Self { code, message_key }
}
}
app/src/recording/dto.rs:
impl From<RecordingError> for IpcError {
fn from(error: RecordingError) -> Self {
match error {
RecordingError::RecorderDidNotStart(_) => Self::new("recorder", "errors.recorder"),
RecordingError::FolderNotWritable(_) => Self::new("folder", "errors.folderNotWritable"),
RecordingError::AlreadyRunning => Self::new("busy", "errors.recordingRunning"),
}
}
}