2016-03-23 30 views
4

Error özelliğinin uygulanmasında bir sorunum var. Dizelden veya başka bir veritabanı sürücüsünden bir hata yazmak istiyorum. Ben zaten Error uygulamakta başarısız olduğum için From uygulamak için yakın bile almadım. Kodun derlenmemesine neden olan satır, kod bloğunun sonundakidir.Hata nasıl kullanılır?

use std::fmt; 
use std::error::{self, Error}; 

#[derive(Debug)] 
pub enum MyError { 
    NotFound(String), 
    PersistenceError(Box<Error + Send + Sync>), 
} 

pub type MyResult<T> = Result<T, MyError>; 

impl fmt::Display for MyError { 
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 
     match *self { 
      MyError::NotFound(ref msg) => write!(f, "Not found: {}", msg), 
      MyError::PersistenceError(ref cause) => write!(f, "Persistence error: {}", cause), 
     } 
    } 
} 

impl Error for MyError { 
    fn description(&self) -> &str { 
     match *self { 
      MyError::NotFound(ref msg) => msg, 
      MyError::PersistenceError(ref cause) => cause.description(), 
     } 
    } 

    fn cause(&self) -> Option<&Error> { 
     match *self { 
      MyError::NotFound(_) => None, 
      // `*cause` does not live long enough 
      MyError::PersistenceError(cause) => Some(&*cause), 
     } 
    } 
} 

Ben de denedim:

*cause does not live long enough

MyError::PersistenceError(cause) => Some(&*cause), 

the trait core::marker::Sized is not implemented for the type std::error::Error + Send + Sync + 'static [E0277]

MyError::PersistenceError(ref cause) => Some(cause), 

the trait std::error::Error is not implemented for the type `&Box

MyError::PersistenceError(ref cause) => Some(&cause) 

Fakat bunlardan hiçbiri çalıştı.

cevap

6

Böyle durumlarda print the type of variables yararlıdır:

match *self { 
    MyError::NotFound(_) => None, 
    MyError::PersistenceError(ref cause) => { 
     let() = cause; 
    }, 
} 

Bu cause bir &Box<std::error::Error + Send + Sync> olduğunu söyleyecektir.

Eğer biz bir kez onu dereferans edersek, bir 'a sahip oluruz ve eğer biz ikinci bir kez daha seçersek std::error::Error + Send + Sync (bu gerçek bir tip değil) olacaktır. Daha sonra, örtülü olarak bir &Error:

match *self { 
    MyError::NotFound(_) => None, 
    MyError::PersistenceError(ref cause) => Some(&**cause), 
} 
'a yapılabilecek başka bir referans alabiliriz.
İlgili konular