From 2af7d3fc2f141d9b0e57975efeb9801eb5d378fe Mon Sep 17 00:00:00 2001 From: Blank038 Date: Mon, 4 May 2026 01:31:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(utils):=20=E6=B7=BB=E5=8A=A0=20io=5Ferror?= =?UTF-8?q?=20=E8=BE=85=E5=8A=A9=E5=87=BD=E6=95=B0=E7=94=A8=E4=BA=8E=20IO?= =?UTF-8?q?=20=E9=94=99=E8=AF=AF=E4=B8=8A=E4=B8=8B=E6=96=87=E5=8C=85?= =?UTF-8?q?=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将匿名 os error 包装为包含操作描述和路径的友好错误信息, 避免出现无法定位问题来源的原始系统错误。 --- src/utils/file.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/utils/file.rs b/src/utils/file.rs index 29e877b..71519b6 100644 --- a/src/utils/file.rs +++ b/src/utils/file.rs @@ -1,16 +1,22 @@ -use crate::error::Result; +use crate::error::{CliError, Result}; use serde_json::Value; -use std::{fs, path::PathBuf}; +use std::{ + fs, io, + path::{Path, PathBuf}, +}; pub fn read_file_to_json(path: &PathBuf) -> Result { - let file = fs::read_to_string(path)?; - let json: Value = serde_json::from_str(&file)?; - Ok(json) + let content = fs::read_to_string(path).map_err(|e| io_error("读取文件", path, e))?; + serde_json::from_str(&content).map_err(|e| { + CliError::InvalidData(format!("解析 JSON '{}' 失败: {}", path.display(), e)) + }) } pub fn write_json_to_file(path: &PathBuf, value: &Value) -> Result<()> { - let content = serde_json::to_string_pretty(value)?; - fs::write(path, content)?; + let content = serde_json::to_string_pretty(value).map_err(|e| { + CliError::InvalidData(format!("序列化 JSON '{}' 失败: {}", path.display(), e)) + })?; + fs::write(path, content).map_err(|e| io_error("写入文件", path, e))?; Ok(()) } @@ -28,3 +34,12 @@ pub fn find_project_dir(path: &Option) -> Result { let path = path.as_deref().unwrap_or("."); Ok(PathBuf::from(path)) } + +/// Wraps an [`io::Error`] with the operation name and path so error messages +/// stop being anonymous "os error 3" strings. +pub fn io_error(op: &str, path: &Path, err: io::Error) -> CliError { + CliError::Io(io::Error::new( + err.kind(), + format!("{} '{}' 失败: {}", op, path.display(), err), + )) +}