use crate::{Error, ErrorKind, ErrorReport};
#[cfg(nightly)]
pub use error_stack::iter::{RequestRef, RequestValue};
pub trait ErrorInspectExt {
fn current_kind(&self) -> &ErrorKind;
fn has_kind(&self, kind: ErrorKind) -> bool;
fn contains_context<C>(&self) -> bool
where
C: Send + Sync + 'static;
fn attachment_ref<A>(&self) -> Option<&A>
where
A: Send + Sync + 'static;
}
impl ErrorInspectExt for Error {
fn current_kind(&self) -> &ErrorKind {
self.current_context()
}
fn has_kind(&self, kind: ErrorKind) -> bool {
self.frames()
.filter_map(|frame| frame.downcast_ref::<ErrorKind>())
.copied()
.any(|current| current == kind)
}
fn contains_context<C>(&self) -> bool
where
C: Send + Sync + 'static,
{
self.contains::<C>()
}
fn attachment_ref<A>(&self) -> Option<&A>
where
A: Send + Sync + 'static,
{
self.downcast_ref::<A>()
}
}
pub fn contains_type<C, T>(report: &ErrorReport<C>) -> bool
where
C: Send + Sync + 'static,
T: Send + Sync + 'static,
{
report.contains::<T>()
}
pub fn downcast_ref<C, T>(report: &ErrorReport<C>) -> Option<&T>
where
C: Send + Sync + 'static,
T: Send + Sync + 'static,
{
report.downcast_ref::<T>()
}
#[cfg(nightly)]
pub trait NightlyErrorInspectExt {
fn request_refs<T>(&self) -> RequestRef<'_, T>
where
T: ?Sized + Send + Sync + 'static;
fn request_values<T>(&self) -> RequestValue<'_, T>
where
T: Send + Sync + 'static;
}
#[cfg(nightly)]
impl<C> NightlyErrorInspectExt for ErrorReport<C> {
fn request_refs<T>(&self) -> RequestRef<'_, T>
where
T: ?Sized + Send + Sync + 'static,
{
self.request_ref::<T>()
}
fn request_values<T>(&self) -> RequestValue<'_, T>
where
T: Send + Sync + 'static,
{
self.request_value::<T>()
}
}
#[cfg(nightly)]
pub fn request_refs<C, T>(report: &ErrorReport<C>) -> RequestRef<'_, T>
where
T: ?Sized + Send + Sync + 'static,
{
report.request_ref::<T>()
}
#[cfg(nightly)]
pub fn request_values<C, T>(report: &ErrorReport<C>) -> RequestValue<'_, T>
where
T: Send + Sync + 'static,
{
report.request_value::<T>()
}
#[cfg(test)]
mod tests {
use super::{ErrorInspectExt, contains_type, downcast_ref};
use crate::{Error, ErrorKind, attachment::Operation};
use error_stack::Report;
use thiserror::Error;
#[derive(Debug, Error, PartialEq, Eq)]
#[error("decode failed")]
struct DecodeContext;
#[test]
fn test_current_kind_returns_public_context() {
let report: Error = Report::new(ErrorKind::InvalidState);
assert_eq!(report.current_kind(), &ErrorKind::InvalidState);
}
#[test]
fn test_has_kind_checks_public_kind_in_stack() {
let report: Error = Report::new(DecodeContext)
.attach(Operation("decode_frame"))
.change_context(ErrorKind::Dependency);
assert!(report.has_kind(ErrorKind::Dependency));
assert!(!report.has_kind(ErrorKind::Timeout));
}
#[test]
fn test_contains_context_detects_inner_typed_context() {
let report: Error = Report::new(DecodeContext).change_context(ErrorKind::Internal);
assert!(report.contains_context::<DecodeContext>());
assert!(!report.contains_context::<Operation>());
}
#[test]
fn test_attachment_ref_returns_latest_matching_attachment() {
let report: Error = Report::new(ErrorKind::Internal)
.attach(Operation("first"))
.attach(Operation("second"));
assert_eq!(
report.attachment_ref::<Operation>(),
Some(&Operation("second"))
);
}
#[test]
fn test_generic_helpers_work_for_any_report_type() {
let report = Report::new(DecodeContext).attach(Operation("decode"));
assert!(contains_type::<DecodeContext, DecodeContext>(&report));
assert!(contains_type::<DecodeContext, Operation>(&report));
assert_eq!(
downcast_ref::<DecodeContext, Operation>(&report),
Some(&Operation("decode"))
);
}
}
#[cfg(all(test, nightly))]
mod nightly_tests {
use super::{NightlyErrorInspectExt, request_refs, request_values};
use crate::{Error, ErrorKind, attachment::Operation};
use error_stack::Report;
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
struct Suggestion(&'static str);
impl fmt::Display for Suggestion {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str(self.0)
}
}
#[derive(Debug, PartialEq, Eq)]
struct ProvidedContext {
retry: u32,
code: u16,
}
impl fmt::Display for ProvidedContext {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
fmt,
"provided context retry={} code={}",
self.retry, self.code
)
}
}
impl std::error::Error for ProvidedContext {
fn provide<'a>(&'a self, request: &mut core::error::Request<'a>) {
request.provide_ref(&self.retry);
request.provide_value(u64::from(self.code));
}
}
#[test]
fn test_request_refs_enumerates_all_matching_attachments() {
let report: Error = Report::new(ErrorKind::Internal)
.attach(Suggestion("first"))
.attach(Suggestion("second"))
.attach(Operation("decode"));
let suggestions = report
.request_refs::<Suggestion>()
.map(|suggestion| suggestion.0)
.collect::<Vec<_>>();
assert_eq!(suggestions, vec!["second", "first"]);
}
#[test]
fn test_request_values_enumerates_all_provided_values_in_recent_first_order() {
let report = Report::new(ProvidedContext { retry: 1, code: 10 })
.change_context(ProvidedContext { retry: 2, code: 20 });
let retries = report.request_refs::<u32>().copied().collect::<Vec<_>>();
let codes = report.request_values::<u64>().collect::<Vec<_>>();
assert_eq!(retries, vec![2, 1]);
assert_eq!(codes, vec![20, 10]);
}
#[test]
fn test_generic_request_helpers_work_for_any_report_type() {
let report = Report::new(ProvidedContext { retry: 7, code: 70 })
.attach(Suggestion("check input"))
.change_context(ProvidedContext { retry: 8, code: 80 });
let suggestions = request_refs::<ProvidedContext, Suggestion>(&report)
.map(|suggestion| suggestion.0)
.collect::<Vec<_>>();
let codes = request_values::<ProvidedContext, u64>(&report).collect::<Vec<_>>();
assert_eq!(suggestions, vec!["check input"]);
assert_eq!(codes, vec![80, 70]);
}
}