2017-05-25 21 views
0

我使用xml-rs來做一些xml解析,並且有一些特殊情況下我想發出自定義xml::reader::Error。此錯誤結構實現爲:使用xml-rs xml :: reader :: Error返回自定義錯誤

pub struct Error { 
    pos: TextPosition, 
    kind: ErrorKind, 
} 

poskind屬性是私有的,所以我不能手動實例化一個Error,並沒有new()方法或類似的東西。

我這是什麼From實現:

impl<'a, P, M> From<(&'a P, M)> for Error where P: Position, M: Into<Cow<'static, str>> { 
    fn from(orig: (&'a P, M)) -> Self { 
     Error{ 
      pos: orig.0.position(), 
      kind: ErrorKind::Syntax(orig.1.into()) 
     } 
    } 
} 

我可以用它來實例化一個自定義錯誤,我需要一個P這意味着它實現xml::common::Position性狀的類型和M這是一個Into<Cow<'static, str>>

對於,P,我想我可以使用xml::reader::EventReader,因爲它實現xml::common::Position。但我不知道如何獲得Into<Cow<'static, str>>

我試圖做這樣的事情:

(event_reader, "custom error").into() 

但它不工作,我想是因爲"custom error"不能轉換到Into<Cow<'static, str>>或類似的東西。

我收到的錯誤消息是這一個:

error[E0277]: the trait bound `xml::reader::Error: std::convert::From<(xml::EventReader<std::io::BufReader<&[u8]>>, &str)>` is not satisfied 
    --> src/main.rs:234:78 
    | 
234 |          _ => return Err((event_reader, "custom error").into()), 
    |                     ^^^^ the trait `std::convert::From<(xml::EventReader<std::io::BufReader<&[u8]>>, &str)>` is not implemented for `xml::reader::Error` 
    | 
    = help: the following implementations were found: 
       <xml::reader::Error as std::convert::From<(&'a P, M)>> 
       <xml::reader::Error as std::convert::From<xml::util::CharReadError>> 
       <xml::reader::Error as std::convert::From<std::io::Error>> 
    = note: required because of the requirements on the impl of `std::convert::Into<xml::reader::Error>` for `(xml::EventReader<std::io::BufReader<&[u8]>>, &str)` 

可以看出,從錯誤,鏽就是沒辦法把我(event_reader, "custom error")元組轉換爲可用xml::reader::Error as std::convert::From<(&'a P, M)>實施。

這就是我想知道爲什麼以及如何解決。

+1

你並不擁有'XML :: Error',所以創建錯誤的定製情況不健全的權利。實際上建議您推出自己的錯誤類型。 –

+1

另外,請在這些代碼片段中包含編譯器的錯誤消息。 –

+0

Hello @ E_net4我在主要問題信息中添加了錯誤信息。另外,我知道我可以創建自己的錯誤類型,現在這是我用來處理代碼的解決方法..但是對於這種情況,我想使用'xml :: reader :: Error',因爲我看到這個錯誤作爲xml語法錯誤。 – Sassa

回答

1

問題是我沒有將&添加到event_reader。添加它解決了該問題,現在From實現被稱爲我可以實例化一個xml::reader::Error

(&event_reader, "custom error").into() 
+1

儘管在技術上這個編譯和工作,我不認爲這是一個**好**的想法。如果圖書館希望你提供你想要的任何自定義錯誤類型,他們會暴露出更明顯的方式。這似乎更接近濫用意外的公共功能。 – Shepmaster

相關問題