[英]How to make error-chain errors compatible with Failure errors?
給出以下代碼:
extern crate dotenv; // v0.11.0
#[macro_use]
extern crate failure; // v0.1.1
#[derive(Debug, Fail)]
#[fail(display = "oh no")]
pub struct Error(dotenv::Error);
由於error-chain
(v0.11,最新版本)不能保證其包裝錯誤是Sync
( 打開PR以解決問題 ),我收到一條錯誤消息,說明沒有為dotenv::Error
實現Sync
:
error[E0277]: the trait bound `std::error::Error + std::marker::Send + 'static: std::marker::Sync` is not satisfied
--> src/main.rs:5:17
|
5 | #[derive(Debug, Fail)]
| ^^^^ `std::error::Error + std::marker::Send + 'static` cannot be shared between threads safely
|
= help: the trait `std::marker::Sync` is not implemented for `std::error::Error + std::marker::Send + 'static`
= note: required because of the requirements on the impl of `std::marker::Sync` for `std::ptr::Unique<std::error::Error + std::marker::Send + 'static>`
= note: required because it appears within the type `std::boxed::Box<std::error::Error + std::marker::Send + 'static>`
= note: required because it appears within the type `std::option::Option<std::boxed::Box<std::error::Error + std::marker::Send + 'static>>`
= note: required because it appears within the type `error_chain::State`
= note: required because it appears within the type `dotenv::Error`
= note: required because it appears within the type `Error`
什么是最小量的樣板/工作,我可以讓這些類型很好地一起玩? 我能想到的最簡單的事情就是添加一個ErrorWrapper
newtype,這樣我就可以在Arc<Mutex<ERROR_CHAIN_TYPE>>
上實現Error
:
use std::fmt::{self, Debug, Display, Formatter};
use std::sync::{Arc, Mutex};
#[derive(Debug, Fail)]
#[fail(display = "oh no")]
pub struct Error(ErrorWrapper<dotenv::Error>);
#[derive(Debug)]
struct ErrorWrapper<T>(Arc<Mutex<T>>)
where
T: Debug;
impl<T> Display for ErrorWrapper<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "oh no!")
}
}
impl<T> ::std::error::Error for ErrorWrapper<T>
where
T: Debug,
{
fn description(&self) -> &str {
"whoops"
}
}
// ... plus a bit more for each `From<T>` that needs to be converted into
// `ErrorWrapper`
這是正確的方法嗎? 對於那些不需要它的東西,是否會有更少的代碼/運行時成本轉換為Arc<Mutex<T>>
?
我唯一可以建議刪除Arc
類型。
如果你有一些不是Sync
東西然后換成Mutex
類型,那么要將error-chain
與failure
集成,只需包裝dotenv::Error
:
#[macro_use]
extern crate failure;
extern crate dotenv;
use std::sync::Mutex;
#[derive(Debug, Fail)]
#[fail(display = "oh no")]
pub struct Error(Mutex<dotenv::Error>);
fn main() {
match dotenv::dotenv() {
Err(e) => {
let err = Error(Mutex::new(e));
println!("{}", err)
}
_ => (),
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.