一个像Box<dyn std::error::Error>的类型可以构建于任意的特定具体错误,可以通过Display打印输出,并且可以通过动态地向下转换进行可选的暴露。anyhow[5]就是这种风格的最佳示例。 std::io::Error的这种情况比较有趣,是因为它想同时做到以上两点甚至更多。 这是std,所以封装和面向未来是最重要的。 来自操作系统的 ...
custom_error.rs: usestd::error::Error;usestd::fmt;usestd::fmt::Display;// 自定义错误类型,包含文件路径信息#[derive(Debug)]pubstructMyError{ msg:String, source:String, }// 为自定义错误类型实现Error traitimplErrorforMyError{}// 实现Display trait,以便于打印错误信息implfmt::DisplayforMyError{...
use std::io::Error;fnmain(){letpath="/tmp/dat";//文件路径matchread_file(path){//判断方法结果Ok(file)=>{println!("{}",file)}//OK 代表读取到文件内容,正确打印文件内容Err(e)=>{println!("{} {}",path,e)}//Err代表结果不存在,打印错误结果}}fnread_file(path:&str)->Result<String,...
std::error 模块:https://doc.rust-lang.org/std/error/index.html [27] std::panic 模块:https://doc.rust-lang.org/std/panic/index.html [28] std::option 模块:https://doc.rust-lang.org/std/option/index.html [29] std::result 模块:https://doc.rust-lang.org/std/result/index.html [30...
目前为止,我们将所有的输出都println!到了终端。大部分终端都提供了两种输出:标准输出(standard output,stdout)对应通用信息,标准错误(standard error,stderr)则用于错误信息。这种区别允许用户选择将程序正常输出定向到一个文件中并仍将错误信息打印到屏幕上。
use std::error::Error; use std::fmt; #[derive(Debug)] struct MyError { details: String } impl MyError { fn new(msg: &str) -> MyError { MyError{details: msg.to_string()} } } impl fnt::Display for MyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Reuslt { ...
failure是rust-lang-nursery下的一个库,可以说是根正苗红的rust库了。其目标是取代基于std::eror::Error的错误处理。 failure有两个核心组件 Fail: 定制错误类型用的trait Error: 只要实现了Fail,就能转化为该结构体 Fail trait Fail trait被用来取代std::error::Error。它提供了backtrace和cause方法去获取错误的...
接受几个 std::error::Error 相关实现的非 'static 生命周期 impl<Fd: AsFd> impl take ?Sized impl From<TryReserveError> for io::Error 兼容性说明 Rust 1.78 增加了其对 Windows 10 的最低要求,针对以下目标: x86_64-pc-windows-msvc i686-pc-windows-msvc ...
而得益于std::error::Error所做的修改,它anyhow::Error是与std::error::Error兼容的。也就是说,对于自定义的错误类型,只需要实现std::error::Error即可。这对于程序的兼容性是一大利好,也因此failure库被日渐废弃。而thiserror正是方便大家为自定义的错误使用宏实现std::error::Error而设计的。
rust 中的错误类型,位于 std::io::ErrorKind 下: pubenumErrorKind{ /// An entity was not found, often a file. #[stable(feature ="rust1", since ="1.0.0")] NotFound, /// The operation lacked the necessary privileges to complete. ...