本文介绍了如何为所有现有错误实现错误包装器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在所有函数中使用我自定义的错误类型,我需要包装现有的标准错误,以便 ?
运算符会成功.
I want to use my customised error type in all functions and I need to wrap the existing standard errors so that the ?
operator will succeed.
这是我正在做的:
use std::{error::Error, fmt, fs};
#[derive(Debug)]
enum MyError {
A,
B,
}
impl fmt::Display for MyError {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
}
impl Error for MyError {
fn description(&self) -> &str {
""
}
}
trait NotMyError {}
impl<T: NotMyError + Error> From<T> for MyError {
fn from(_: T) -> MyError {
MyError::A
}
}
fn test() -> Result<(), MyError> {
fs::read_dir("test")?;
Ok(())
}
fn main() {}
编译器抱怨:
error[E0277]: the trait bound `std::io::Error: NotMyError` is not satisfied
--> src/main.rs:30:5
|
30 | fs::read_dir("test")?;
| ^^^^^^^^^^^^^^^^^^^^^ the trait `NotMyError` is not implemented for `std::io::Error`
|
= note: required because of the requirements on the impl of `std::convert::From<std::io::Error>` for `MyError`
= note: required by `std::convert::From::from`
推荐答案
一篇关于它.要为您的错误获得一流的支持,您需要做两件事:
There's an excellent post about it. To get first-class support for your error you need to do two things:
- 实现
Error
trait 适合您的类型. - 为要与
?
运算符(quick_error crate 有助于自动执行此操作.
- Implement the
Error
trait for your type. - Implement
std::convert::From
for error types you want to use seamlessly with the?
operator (the quick_error crate helps automate this).
这篇关于如何为所有现有错误实现错误包装器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!