#![unstable]
use std::error::Error;
use std::io::IoError;
use std::error::FromError;
use response::Response;
use self::ErrorKind::{TransientError, PermanentError, UnknownError, InternalIoError};
#[deriving(PartialEq, Eq, Clone, Show)]
pub enum ErrorKind {
TransientError(Response),
PermanentError(Response),
UnknownError(String),
InternalIoError(IoError),
}
#[deriving(PartialEq, Eq, Clone, Show)]
pub struct SmtpError {
pub kind: ErrorKind,
pub desc: &'static str,
pub detail: Option<String>,
}
impl FromError<IoError> for SmtpError {
fn from_error(err: IoError) -> SmtpError {
SmtpError {
kind: InternalIoError(err),
desc: "An internal IO error ocurred.",
detail: None,
}
}
}
impl FromError<(ErrorKind, &'static str)> for SmtpError {
fn from_error((kind, desc): (ErrorKind, &'static str)) -> SmtpError {
SmtpError {
kind: kind,
desc: desc,
detail: None,
}
}
}
impl FromError<Response> for SmtpError {
fn from_error(response: Response) -> SmtpError {
let kind = match response.code/100 {
4 => TransientError(response),
5 => PermanentError(response),
_ => UnknownError(response.to_string()),
};
let desc = match kind {
TransientError(_) => "a permanent error occured during the SMTP transaction",
PermanentError(_) => "a permanent error occured during the SMTP transaction",
UnknownError(_) => "an unknown error occured during the SMTP transaction",
InternalIoError(_) => "an I/O error occurred",
};
SmtpError {
kind: kind,
desc: desc,
detail: None,
}
}
}
impl FromError<&'static str> for SmtpError {
fn from_error(string: &'static str) -> SmtpError {
SmtpError {
kind: UnknownError(string.to_string()),
desc: "an unknown error occured during the SMTP transaction",
detail: None,
}
}
}
impl Error for SmtpError {
fn description(&self) -> &str {
match self.kind {
InternalIoError(ref err) => err.desc,
_ => self.desc,
}
}
fn detail(&self) -> Option<String> {
match self.kind {
TransientError(ref response) => Some(response.to_string()),
PermanentError(ref response) => Some(response.to_string()),
UnknownError(ref string) => Some(string.to_string()),
InternalIoError(ref err) => err.detail.clone(),
}
}
fn cause(&self) -> Option<&Error> {
match self.kind {
InternalIoError(ref err) => Some(&*err as &Error),
_ => None,
}
}
}
pub type SmtpResult = Result<Response, SmtpError>;