use std::backtrace::Backtrace;
use std::fmt;
use std::sync::Arc;
use crate::{Code, ErrorCode};
pub trait Fault: std::error::Error + Send + Sync + 'static {
fn code(&self) -> Code;
fn retryable(&self) -> bool {
false
}
fn backtrace(&self) -> Option<&Backtrace> {
None
}
}
#[derive(Clone, Debug)]
pub struct Error {
fault: Arc<dyn Fault>,
stack: Vec<String>,
}
impl Error {
#[must_use]
pub fn new(code: impl ErrorCode, message: impl Into<String>) -> Error {
Failure::new(code, message).into()
}
#[must_use]
pub fn code(&self) -> Code {
self.fault.code()
}
#[must_use]
pub fn code_as<C: ErrorCode>(&self) -> Option<C> {
self.code().get()
}
#[must_use]
pub fn is<C: ErrorCode>(&self, code: C) -> bool {
self.code().is(code)
}
#[must_use]
pub fn retryable(&self) -> bool {
self.fault.retryable()
}
#[must_use]
pub fn stack(&self) -> &[String] {
&self.stack
}
#[must_use]
pub fn backtrace(&self) -> Option<&Backtrace> {
self.fault.backtrace()
}
#[must_use]
pub fn downcast_ref<F: Fault>(&self) -> Option<&F> {
let fault: &(dyn std::error::Error + 'static) = &*self.fault;
fault.downcast_ref()
}
#[must_use]
pub fn context(mut self, frame: impl fmt::Display) -> Error {
let frame = frame.to_string();
if !frame.is_empty() {
self.stack.insert(0, frame);
}
self
}
}
impl<F: Fault> From<F> for Error {
fn from(fault: F) -> Error {
Error {
fault: Arc::new(fault),
stack: Vec::new(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for frame in &self.stack {
write!(f, "{frame}: ")?;
}
write!(f, "{}: {}", self.fault.code(), self.fault)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.fault.source()
}
}
#[derive(Debug)]
pub struct Failure {
code: Code,
message: String,
retryable: bool,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
backtrace: Backtrace,
}
impl Failure {
#[must_use]
pub fn new(code: impl ErrorCode, message: impl Into<String>) -> Failure {
Failure {
code: Code::of(code),
message: message.into(),
retryable: false,
source: None,
backtrace: Backtrace::capture(),
}
}
#[must_use]
pub fn with_retryable(mut self, retryable: bool) -> Failure {
self.retryable = retryable;
self
}
#[must_use]
pub fn with_source(
mut self,
source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
) -> Failure {
self.source = Some(source.into());
self
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Failure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_deref()
.map(|source| source as &(dyn std::error::Error + 'static))
}
}
impl Fault for Failure {
fn code(&self) -> Code {
self.code
}
fn retryable(&self) -> bool {
self.retryable
}
fn backtrace(&self) -> Option<&Backtrace> {
Some(&self.backtrace)
}
}
pub trait Context<T> {
fn context(self, frame: impl fmt::Display) -> Result<T, Error>;
fn with_context<D: fmt::Display>(self, frame: impl FnOnce() -> D) -> Result<T, Error>;
}
impl<T, E: Into<Error>> Context<T> for Result<T, E> {
fn context(self, frame: impl fmt::Display) -> Result<T, Error> {
self.map_err(|error| error.into().context(frame))
}
fn with_context<D: fmt::Display>(self, frame: impl FnOnce() -> D) -> Result<T, Error> {
self.map_err(|error| error.into().context(frame()))
}
}
#[cfg(test)]
mod tests {
use std::error::Error as _;
use super::{Context, Error, Failure};
use crate::RuntimeCode;
#[test]
fn new_is_a_plain_failure() {
let error = Error::new(RuntimeCode::Panicked, "boom");
assert!(error.is(RuntimeCode::Panicked));
assert_eq!(error.code_as::<RuntimeCode>(), Some(RuntimeCode::Panicked));
assert!(!error.retryable());
assert!(error.stack().is_empty());
assert!(error.source().is_none());
assert!(error.backtrace().is_some());
assert_eq!(error.to_string(), "PANICKED: boom");
let failure = error.downcast_ref::<Failure>().map(Failure::message);
assert_eq!(failure, Some("boom"));
}
#[test]
fn failure_keeps_retry_and_the_last_source() {
let error: Error = Failure::new(RuntimeCode::Cancelled, "cannot read")
.with_retryable(true)
.with_source("first")
.with_source(std::io::Error::other("second"))
.into();
assert!(error.retryable());
let source = error.source().map(ToString::to_string);
assert_eq!(source.as_deref(), Some("second"));
assert_eq!(error.to_string(), "CANCELLED: cannot read");
}
#[test]
fn context_prepends_the_outermost_frame() {
let inner: Result<(), Failure> = Err(Failure::new(RuntimeCode::Cancelled, "gone"));
let error = inner
.context("read")
.with_context(|| format!("load {}", 7))
.context("")
.unwrap_err();
assert_eq!(error.stack(), ["load 7", "read"]);
assert_eq!(error.to_string(), "load 7: read: CANCELLED: gone");
}
#[test]
fn with_context_builds_no_frame_on_ok() {
let ok: Result<u8, Error> = Ok(1);
let value = ok.with_context(|| -> String { unreachable!("built on Ok") });
assert_eq!(value.ok(), Some(1));
}
#[test]
fn clone_shares_the_fault() {
let error = Error::new(RuntimeCode::CannotBlock, "wait").context("call");
let copy = error.clone();
assert!(copy.is(RuntimeCode::CannotBlock));
assert_eq!(copy.stack(), ["call"]);
assert_eq!(copy.to_string(), error.to_string());
}
#[test]
fn is_a_std_error() {
let error: Box<dyn std::error::Error + Send + Sync> =
Box::new(Error::new(RuntimeCode::Cancelled, "down"));
assert_eq!(error.to_string(), "CANCELLED: down");
}
}