github_templates/
error.rs

1use failure::{Backtrace, Context, Fail};
2use std::fmt::{self, Display};
3use std::io;
4use std::result;
5
6/// A specialized [`Result`] type for this crate's operations.
7///
8/// This is generally used to avoid writing out [Error] directly and
9/// is otherwise a direct mapping to [`Result`].
10///
11/// [`Result`]: https://doc.rust-lang.org/nightly/std/result/enum.Result.html
12/// [`Error`]: std.struct.Error.html
13pub type Result<T> = result::Result<T, Error>;
14
15/// A specialized [`Error`] type for this crate's operations.
16///
17/// [`Error`]: https://doc.rust-lang.org/nightly/std/error/trait.Error.html
18#[derive(Debug)]
19pub struct Error {
20  inner: Context<ErrorKind>,
21}
22
23/// A list enumerating the categories of errors in this crate.
24///
25/// This list is intended to grow over time and it is not recommended to
26/// exhaustively match against it.
27///
28/// It is used with the [`Error`] struct.
29///
30/// [`Error`]: std.struct.Error.html
31#[derive(Debug, Fail)]
32pub enum ErrorKind {
33  /// An error caused by log failure.
34  #[fail(display = "An error occurred setting up the logger.")]
35  Log,
36  /// Any error not part of this list.
37  #[fail(display = "Generic error.")]
38  Other,
39  /// An error caused by an IO failure.
40  #[fail(display = "{}", _0)]
41  Io(#[cause] io::Error),
42}
43
44impl Error {
45  /// Access the [`ErrorKind`] member.
46  ///
47  /// [`ErrorKind`]: enum.ErrorKind.html
48  pub fn kind(&self) -> &ErrorKind {
49    &*self.inner.get_context()
50  }
51}
52
53impl Fail for Error {
54  fn cause(&self) -> Option<&Fail> {
55    self.inner.cause()
56  }
57
58  fn backtrace(&self) -> Option<&Backtrace> {
59    self.inner.backtrace()
60  }
61}
62
63impl Display for Error {
64  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65    Display::fmt(&self.inner, f)
66  }
67}
68
69impl From<ErrorKind> for Error {
70  fn from(kind: ErrorKind) -> Error {
71    let inner = Context::new(kind);
72    Error { inner }
73  }
74}
75
76impl From<Context<ErrorKind>> for Error {
77  fn from(inner: Context<ErrorKind>) -> Error {
78    Error { inner }
79  }
80}