Error handling 锈迹斑斑';来源';领域
我正试图使用snafu板条箱进行错误处理,但不断收到错误消息,我的错误枚举结构缺少“源代码”,并且Error handling 锈迹斑斑';来源';领域,error-handling,rust,Error Handling,Rust,我正试图使用snafu板条箱进行错误处理,但不断收到错误消息,我的错误枚举结构缺少“源代码”,并且IntoError未为error实现: //main.rs 使用snafu::{ResultExt,snafu}; #[派生(调试,Snafu)] #[snafu(visibility=“pub(板条箱)”)] 发布枚举错误{ #[snafu(显示(“无法加载库JSON:{}:{}”,JSON_路径,源))] 载货台{ 来源:std::io::错误, json_路径:字符串, }, } //gal
IntoError
未为error
实现:
//main.rs
使用snafu::{ResultExt,snafu};
#[派生(调试,Snafu)]
#[snafu(visibility=“pub(板条箱)”)]
发布枚举错误{
#[snafu(显示(“无法加载库JSON:{}:{}”,JSON_路径,源))]
载货台{
来源:std::io::错误,
json_路径:字符串,
},
}
//gallery.rs
使用snafu::{ResultExt};
使用板条箱::错误:{LoadGallery};
酒吧结构画廊{
名称:String,
}
impl画廊{
pub fn from_json(json_路径:String)->Result{
让configuration=std::fs::read_to_string(&json_path).context(LoadGallery{json_path})?;
好(())
}
}
结果:
let configuration = std::fs::read_to_string(&json_path).context(LoadGallery { json_path })?;
| ^^^^^^^^^^^ missing `source`
let configuration = std::fs::read_to_string(&json_path).context(LoadGallery { json_path })?;
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `IntoError<_>` is not implemented for `Error`
let configuration=std::fs::read_to_string(&json_path).context(LoadGallery{json_path})?;
|^^^^^^^^^^^^^^缺少`源`
让configuration=std::fs::read_to_string(&json_path).context(LoadGallery{json_path})?;
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^未为` Error'实现特性` int`
根据文档中的这个例子,我看不出我做错了什么:
使用snafu::{ResultExt,snafu};
使用std::{fs,io,path::PathBuf};
#[派生(调试,Snafu)]
枚举错误{
#[snafu(显示(“无法从{}:{}读取配置”,path.display(),source))]
ReadConfiguration{source:io::Error,path:PathBuf},
#[snafu(显示(“无法将结果写入{}:{}”,path.display(),source))]
WriteResult{source:io::Error,path:PathBuf},
}
类型Result=std::Result::Result;
fn处理_数据()->结果{
让path=“config.toml”;
让configuration=fs::read_to_string(path).context(ReadConfiguration{path})?;
let path=unpack_config(&configuration);
fs::write(&path,b“我的复杂计算”).context(WriteResult{path})?;
好(())
}
fn解包配置(数据:&str)->&str{
“/some/path/that/notes/exist”
}
这是因为当您构建LoadGallery
时,您正试图构建错误::LoadGallery
。然后,您会得到一个编译错误,说“missingsource
”,因为error::LoadGallery
变量有一个source
字段。直接修复它,只需更改导入的LoadGallery
//不是这个:
//使用板条箱::错误::LoadGallery;
//这个:
使用板条箱::LoadGallery;
为什么??因为为每个错误
的变体生成一个结构。因此,将生成一个struct LoadGallery
。此结构不包含source
字段,因此您可以在不使用source
的情况下构造它并将其传递给,因为它实际上不是Error::LoadGallery
您的from_json()
还需要返回Result
,而不是Result
(您没有类型别名,如示例中所示)
使用板条箱::{错误,LoadGallery};
使用snafu::ResultExt;
酒吧结构画廊{
名称:String,
}
impl画廊{
pub fn from_json(json_路径:String)->Result{
let配置=
std::fs::read_to_string(&json_path).context(LoadGallery{json_path})?;
好(())
}
}
如果您感到好奇,可以使用来检查宏扩展到什么。首先需要通过执行cargo install expand
来安装它。然后您可以在任何项目中执行