use std::fmt;
use std::time::Duration;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RuntimeError {
#[error("configuration: {0}")]
Configuration(String),
#[error("deadline exceeded after {} ms", .elapsed.as_millis())]
DeadlineExceeded {
elapsed: Duration,
},
#[error("limit exceeded: {limit} of {kind}")]
LimitExceeded {
kind: &'static str,
limit: u64,
},
#[error("{context}")]
Other {
context: String,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
}
impl RuntimeError {
pub fn other<E>(context: impl Into<String>, source: E) -> Self
where
E: std::error::Error + Send + Sync + 'static,
{
Self::Other {
context: context.into(),
source: Some(Box::new(source)),
}
}
pub fn message(context: impl Into<String>) -> Self {
Self::Other {
context: context.into(),
source: None,
}
}
}
impl From<String> for RuntimeError {
fn from(context: String) -> Self {
Self::message(context)
}
}
impl From<&str> for RuntimeError {
fn from(context: &str) -> Self {
Self::message(context)
}
}
pub fn chain(error: &dyn std::error::Error) -> String {
let mut text = error.to_string();
let mut source = error.source();
while let Some(cause) = source {
use fmt::Write as _;
let _ = write!(text, ": {cause}");
source = cause.source();
}
text
}