]> git.lizzy.rs Git - rust.git/blob - src/rustbook/error.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / rustbook / error.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error handling utilities. WIP.
12
13 use std::fmt;
14 use std::fmt::{Debug, Formatter};
15
16 use std::old_io::IoError;
17
18 pub type CliError = Box<Error + 'static>;
19 pub type CliResult<T> = Result<T, CliError>;
20
21 pub type CommandError = Box<Error + 'static>;
22 pub type CommandResult<T> = Result<T, CommandError>;
23
24 pub trait Error {
25     fn description(&self) -> &str;
26
27     fn detail(&self) -> Option<&str> { None }
28     fn cause(&self) -> Option<&Error> { None }
29 }
30
31 pub trait FromError<E> {
32     fn from_err(err: E) -> Self;
33 }
34
35 impl Debug for Box<Error + 'static> {
36     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
37         write!(f, "{}", self.description())
38     }
39 }
40
41 impl<E: Error + 'static> FromError<E> for Box<Error + 'static> {
42     fn from_err(err: E) -> Box<Error + 'static> {
43         box err as Box<Error>
44     }
45 }
46
47 impl<'a> Error for &'a str {
48     fn description<'b>(&'b self) -> &'b str {
49         *self
50     }
51 }
52
53 impl Error for String {
54     fn description<'a>(&'a self) -> &'a str {
55         &self[]
56     }
57 }
58
59 impl<'a> Error for Box<Error + 'a> {
60     fn description(&self) -> &str { (**self).description() }
61     fn detail(&self) -> Option<&str> { (**self).detail() }
62     fn cause(&self) -> Option<&Error> { (**self).cause() }
63 }
64
65 impl FromError<()> for () {
66     fn from_err(_: ()) -> () { () }
67 }
68
69 impl FromError<IoError> for IoError {
70     fn from_err(error: IoError) -> IoError { error }
71 }
72
73 impl Error for IoError {
74     fn description(&self) -> &str {
75         self.desc
76     }
77     fn detail(&self) -> Option<&str> {
78         self.detail.as_ref().map(|s| &s[])
79     }
80 }
81
82
83 //fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,