1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use std::error;
use std::fmt::{self, Display, Formatter};
use std::result;

use Class;

pub type Result<T> = result::Result<T, Error>;

#[derive(Debug, PartialEq)]
pub enum Error {
    ArgumentError(String),
    TypeError(String),
}

impl Error {
    /// Converts error to an exception class.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruru::result::Error;
    /// use ruru::{Class, VM};
    ///
    /// # VM::init();
    /// let argument_error = Error::ArgumentError("Argument is missing".to_string());
    /// let type_error = Error::TypeError("Wrong type".to_string());
    ///
    /// assert_eq!(argument_error.to_exception(), Class::from_existing("ArgumentError"));
    /// assert_eq!(type_error.to_exception(), Class::from_existing("TypeError"));
    /// ```
    pub fn to_exception(&self) -> Class {
        let class_name = match *self {
            Error::ArgumentError(_) => "ArgumentError",
            Error::TypeError(_) => "TypeError",
        };

        Class::from_existing(class_name)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", <Error as error::Error>::description(&self))
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::ArgumentError(ref message) | Error::TypeError(ref message) => message,
        }
    }
}