af_core/
error.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7//! Basic error handling.
8
9pub use std::error::Error;
10pub use thiserror::Error;
11
12use crate::prelude::*;
13
14/// An error representing a panic.
15#[derive(Error, From)]
16pub struct Panic {
17  /// The panic value.
18  pub value: Box<dyn Any + Send>,
19}
20
21impl Panic {
22  /// Returns a reference to the panic value if it is a string.
23  pub fn value_str(&self) -> Option<&str> {
24    if let Some(string) = self.value.downcast_ref::<String>() {
25      Some(string)
26    } else if let Some(string) = self.value.downcast_ref::<&'static str>() {
27      Some(string)
28    } else {
29      None
30    }
31  }
32}
33
34impl Debug for Panic {
35  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36    write!(f, "PanicError")?;
37
38    if let Some(value) = self.value_str() {
39      write!(f, "({:?})", value)?;
40    }
41
42    Ok(())
43  }
44}
45
46impl Display for Panic {
47  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48    write!(f, "Panicked")?;
49
50    if let Some(value) = self.value_str() {
51      write!(f, " with `{}`", value)?;
52    }
53
54    write!(f, ".")
55  }
56}