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
84
// Copyright © 2020 Alexandra Frydl
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! A general purpose error type.

pub use af_core_macros::{fail, fail_err as err, fail_when as when, fail_wrap as wrap};

use crate::prelude::*;
use crate::string::SharedString;

/// A generic cloneable error.
#[derive(Clone)]
pub struct Error {
  message: SharedString,
  trace: im::Vector<SharedString>,
}

/// Represents either success (`Ok`) or failure (`Err`).
///
/// This type doesn't require any type parameters and defaults to
/// `Result<(), fail::Error>`.
pub type Result<T = (), E = Error> = std::result::Result<T, E>;

/// Create a new [`Error`] from a given error.
pub fn from<T: Into<Error>>(err: T) -> Error {
  err.into()
}

impl Error {
  /// Creates a new error with the given message.
  pub fn new(message: impl Into<SharedString>) -> Self {
    Self { message: message.into(), trace: default() }
  }

  /// Sets the cause of this error.
  pub fn set_cause(&mut self, cause: impl Into<Self>) {
    let cause = cause.into();

    self.trace = cause.trace;
    self.trace.push_front(cause.message);
  }

  /// Returns a copy of this error with a new cause.
  pub fn with_cause(mut self, cause: impl Into<Self>) -> Self {
    self.set_cause(cause);
    self
  }
}

// Implement `From` to convert from other types of errors.

impl<T> From<T> for Error
where
  T: std::error::Error,
{
  fn from(err: T) -> Self {
    Self::new(err.to_string())
  }
}

// Implement formatting.

impl Debug for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    Debug::fmt(&self.message, f)
  }
}

impl Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    Display::fmt(&self.message, f)?;

    if f.alternate() {
      for err in &self.trace {
        write!(f, "\n * {:#}", fmt::indent("", "   ", err))?;
      }
    }

    Ok(())
  }
}