about summary refs log tree commit diff
path: root/src/rustbook/error.rs
blob: 1c10a270acc6c9ff1d2e708967ca0a8e5ca4a4f4 (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Error handling utilities. WIP.

use std::fmt;
use std::fmt::{Debug, Formatter};

use std::old_io::IoError;

pub type CliError = Box<Error + 'static>;
pub type CliResult<T> = Result<T, CliError>;

pub type CommandError = Box<Error + 'static>;
pub type CommandResult<T> = Result<T, CommandError>;

pub trait Error {
    fn description(&self) -> &str;

    fn detail(&self) -> Option<&str> { None }
    fn cause(&self) -> Option<&Error> { None }
}

pub trait FromError<E> {
    fn from_err(err: E) -> Self;
}

impl Debug for Box<Error + 'static> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error + 'static> FromError<E> for Box<Error + 'static> {
    fn from_err(err: E) -> Box<Error + 'static> {
        box err as Box<Error>
    }
}

impl<'a> Error for &'a str {
    fn description<'b>(&'b self) -> &'b str {
        *self
    }
}

impl Error for String {
    fn description<'a>(&'a self) -> &'a str {
        &self[]
    }
}

impl<'a> Error for Box<Error + 'a> {
    fn description(&self) -> &str { (**self).description() }
    fn detail(&self) -> Option<&str> { (**self).detail() }
    fn cause(&self) -> Option<&Error> { (**self).cause() }
}

impl FromError<()> for () {
    fn from_err(_: ()) -> () { () }
}

impl FromError<IoError> for IoError {
    fn from_err(error: IoError) -> IoError { error }
}

impl Error for IoError {
    fn description(&self) -> &str {
        self.desc
    }
    fn detail(&self) -> Option<&str> {
        self.detail.as_ref().map(|s| &s[])
    }
}


//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,