use std::{error::Error as StdError, fmt, io};
use error_stack::IntoReport;
use crate::{ErrorKind, ErrorReport, Result, TypedResult, attachment::SourceTypeName};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{display_text}")]
pub struct ExternalError {
display_text: String,
debug_text: String,
}
impl ExternalError {
pub fn new(display_text: impl Into<String>, debug_text: impl Into<String>) -> Self {
Self {
display_text: display_text.into(),
debug_text: debug_text.into(),
}
}
pub fn capture<E>(error: &E) -> Self
where
E: fmt::Display + fmt::Debug,
{
Self::new(error.to_string(), format!("{error:?}"))
}
pub fn display_text(&self) -> &str {
&self.display_text
}
pub fn debug_text(&self) -> &str {
&self.debug_text
}
}
impl ClassifyErrorKind for ExternalError {
fn classify_error_kind(&self) -> ErrorKind {
ErrorKind::Other
}
}
pub trait ClassifyErrorKind {
fn classify_error_kind(&self) -> ErrorKind;
}
impl ClassifyErrorKind for ErrorKind {
fn classify_error_kind(&self) -> ErrorKind {
*self
}
}
impl<C> ClassifyErrorKind for ErrorReport<C>
where
C: ClassifyErrorKind + Send + Sync + 'static,
{
fn classify_error_kind(&self) -> ErrorKind {
self.current_context().classify_error_kind()
}
}
impl ClassifyErrorKind for io::Error {
fn classify_error_kind(&self) -> ErrorKind {
classify_io_error(self)
}
}
pub fn classify_io_error(error: &io::Error) -> ErrorKind {
match error.kind() {
io::ErrorKind::NotFound => ErrorKind::NotFound,
io::ErrorKind::PermissionDenied => ErrorKind::PermissionDenied,
io::ErrorKind::AlreadyExists => ErrorKind::AlreadyExists,
io::ErrorKind::TimedOut => ErrorKind::Timeout,
io::ErrorKind::InvalidInput => ErrorKind::InvalidInput,
io::ErrorKind::InvalidData => ErrorKind::Corrupted,
io::ErrorKind::WouldBlock => ErrorKind::Busy,
io::ErrorKind::Interrupted => ErrorKind::Cancelled,
_ => ErrorKind::Io,
}
}
pub fn source_type_name_of<E>() -> SourceTypeName {
SourceTypeName::of::<E>()
}
pub trait InteropResultExt<T, E>: Sized {
fn into_external_report(self) -> core::result::Result<T, ErrorReport<ExternalError>>
where
E: fmt::Display + fmt::Debug;
fn into_external_report_with<F>(
self,
f: F,
) -> core::result::Result<T, ErrorReport<ExternalError>>
where
F: FnOnce(&E) -> ExternalError;
fn into_external_error_by<F>(self, f: F) -> Result<T>
where
E: fmt::Display + fmt::Debug,
F: FnOnce(&E) -> ErrorKind;
fn into_external_error_with<F>(self, f: F) -> Result<T>
where
F: FnOnce(&E) -> (ErrorKind, ExternalError);
fn into_external_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
where
C: StdError + Send + Sync + 'static,
E: fmt::Display + fmt::Debug,
F: FnOnce(&E) -> C;
fn into_external_typed_with<C, F>(self, f: F) -> TypedResult<T, C>
where
C: StdError + Send + Sync + 'static,
F: FnOnce(&E) -> (C, ExternalError);
fn into_external_classified_error(self) -> Result<T>
where
E: fmt::Display + fmt::Debug + ClassifyErrorKind;
fn into_error_by<F>(self, f: F) -> Result<T>
where
E: IntoReport,
F: FnOnce(&E) -> ErrorKind;
fn into_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
where
C: StdError + Send + Sync + 'static,
E: IntoReport,
F: FnOnce(&E) -> C;
fn into_classified_error(self) -> Result<T>
where
E: IntoReport + ClassifyErrorKind;
fn into_report_with_source(
self,
) -> core::result::Result<T, ErrorReport<<E as IntoReport>::Context>>
where
E: IntoReport + Send + Sync + 'static;
}
impl<T, E> InteropResultExt<T, E> for core::result::Result<T, E> {
fn into_external_report(self) -> core::result::Result<T, ErrorReport<ExternalError>>
where
E: fmt::Display + fmt::Debug,
{
self.into_external_report_with(ExternalError::capture)
}
fn into_external_report_with<F>(
self,
f: F,
) -> core::result::Result<T, ErrorReport<ExternalError>>
where
F: FnOnce(&E) -> ExternalError,
{
match self {
Ok(value) => Ok(value),
Err(error) => {
Err(error_stack::Report::new(f(&error)).attach(SourceTypeName::of::<E>()))
}
}
}
fn into_external_error_by<F>(self, f: F) -> Result<T>
where
E: fmt::Display + fmt::Debug,
F: FnOnce(&E) -> ErrorKind,
{
self.into_external_error_with(|error| (f(error), ExternalError::capture(error)))
}
fn into_external_error_with<F>(self, f: F) -> Result<T>
where
F: FnOnce(&E) -> (ErrorKind, ExternalError),
{
match self {
Ok(value) => Ok(value),
Err(error) => {
let (kind, external) = f(&error);
Err(error_stack::Report::new(external)
.attach(SourceTypeName::of::<E>())
.change_context(kind))
}
}
}
fn into_external_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
where
C: StdError + Send + Sync + 'static,
E: fmt::Display + fmt::Debug,
F: FnOnce(&E) -> C,
{
self.into_external_typed_with(|error| (f(error), ExternalError::capture(error)))
}
fn into_external_typed_with<C, F>(self, f: F) -> TypedResult<T, C>
where
C: StdError + Send + Sync + 'static,
F: FnOnce(&E) -> (C, ExternalError),
{
match self {
Ok(value) => Ok(value),
Err(error) => {
let (context, external) = f(&error);
Err(error_stack::Report::new(external)
.attach(SourceTypeName::of::<E>())
.change_context(context))
}
}
}
fn into_external_classified_error(self) -> Result<T>
where
E: fmt::Display + fmt::Debug + ClassifyErrorKind,
{
self.into_external_error_by(ClassifyErrorKind::classify_error_kind)
}
fn into_error_by<F>(self, f: F) -> Result<T>
where
E: IntoReport,
F: FnOnce(&E) -> ErrorKind,
{
match self {
Ok(value) => Ok(value),
Err(error) => {
let kind = f(&error);
Err(error.into_report().change_context(kind))
}
}
}
fn into_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
where
C: StdError + Send + Sync + 'static,
E: IntoReport,
F: FnOnce(&E) -> C,
{
match self {
Ok(value) => Ok(value),
Err(error) => {
let context = f(&error);
Err(error.into_report().change_context(context))
}
}
}
fn into_classified_error(self) -> Result<T>
where
E: IntoReport + ClassifyErrorKind,
{
self.into_error_by(ClassifyErrorKind::classify_error_kind)
}
fn into_report_with_source(
self,
) -> core::result::Result<T, ErrorReport<<E as IntoReport>::Context>>
where
E: IntoReport + Send + Sync + 'static,
{
match self {
Ok(value) => Ok(value),
Err(error) => Err(error.into_report().attach(SourceTypeName::of::<E>())),
}
}
}
#[cfg(test)]
mod tests {
use super::{
ClassifyErrorKind, ExternalError, InteropResultExt, classify_io_error, source_type_name_of,
};
use crate::{ErrorKind, attachment::SourceTypeName};
use error_stack::Report;
use std::{fmt, rc::Rc};
use thiserror::Error;
#[derive(Debug, Error)]
#[error("third-party decode failed")]
struct ThirdPartyDecodeError;
#[derive(Debug, Error, PartialEq, Eq)]
enum ExternalContext {
#[error("failed to decode third-party payload")]
Decode,
#[error("legacy parser rejected input")]
LegacyParse,
}
impl ClassifyErrorKind for ThirdPartyDecodeError {
fn classify_error_kind(&self) -> ErrorKind {
ErrorKind::Dependency
}
}
#[derive(Debug)]
struct BorrowedLegacyError<'a> {
input: &'a str,
shared: Rc<String>,
}
impl fmt::Display for BorrowedLegacyError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"legacy parser rejected `{}` from {}",
self.input, self.shared
)
}
}
impl ClassifyErrorKind for BorrowedLegacyError<'_> {
fn classify_error_kind(&self) -> ErrorKind {
ErrorKind::InvalidInput
}
}
#[derive(Debug)]
struct RawForeignCode {
code: u16,
subsystem: &'static str,
}
#[test]
fn test_classify_io_error_maps_stable_common_cases() {
assert_eq!(
classify_io_error(&std::io::Error::from(std::io::ErrorKind::NotFound)),
ErrorKind::NotFound
);
assert_eq!(
classify_io_error(&std::io::Error::from(std::io::ErrorKind::TimedOut)),
ErrorKind::Timeout
);
assert_eq!(
classify_io_error(&std::io::Error::from(std::io::ErrorKind::InvalidData)),
ErrorKind::Corrupted
);
assert_eq!(
classify_io_error(&std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
ErrorKind::Io
);
}
#[test]
fn test_into_error_by_can_classify_raw_std_result() {
let report = Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::NotFound))
.into_error_by(classify_io_error)
.expect_err("expected report");
assert_eq!(report.current_context(), &ErrorKind::NotFound);
assert!(report.contains::<std::io::Error>());
}
#[test]
fn test_into_typed_by_can_build_context_from_original_error() {
let report = Err::<(), ThirdPartyDecodeError>(ThirdPartyDecodeError)
.into_typed_by(|_| ExternalContext::Decode)
.expect_err("expected typed report");
assert_eq!(report.current_context(), &ExternalContext::Decode);
assert!(report.contains::<ThirdPartyDecodeError>());
}
#[test]
fn test_into_classified_error_uses_trait_based_mapping() {
let report = Err::<(), ThirdPartyDecodeError>(ThirdPartyDecodeError)
.into_classified_error()
.expect_err("expected report");
assert_eq!(report.current_context(), &ErrorKind::Dependency);
assert!(report.contains::<ThirdPartyDecodeError>());
}
#[test]
fn test_into_report_with_source_attaches_original_error_type() {
let report =
Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
.into_report_with_source()
.expect_err("expected typed report");
assert!(report.contains::<std::io::Error>());
assert_eq!(
report.downcast_ref::<SourceTypeName>(),
Some(&SourceTypeName::of::<std::io::Error>())
);
}
#[test]
fn test_source_type_name_helper_matches_attachment_constructor() {
assert_eq!(
source_type_name_of::<ThirdPartyDecodeError>(),
SourceTypeName::of::<ThirdPartyDecodeError>()
);
}
#[test]
fn test_report_of_classifiable_context_can_be_reclassified_again() {
let report = Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::TimedOut))
.into_classified_error()
.expect_err("expected public report");
let reclassified = Err::<(), Report<ErrorKind>>(report)
.into_classified_error()
.expect_err("expected reclassified report");
assert_eq!(reclassified.current_context(), &ErrorKind::Timeout);
assert!(reclassified.contains::<std::io::Error>());
assert!(reclassified.contains::<ErrorKind>());
}
#[test]
fn test_external_report_can_snapshot_non_error_non_send_sync_non_static_value() {
let report = {
let input = String::from("bad-token");
let shared = Rc::new(String::from("legacy_parser"));
Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
input: &input,
shared,
})
.into_external_report()
.expect_err("expected external report")
};
let captured = report
.downcast_ref::<ExternalError>()
.expect("external snapshot should exist");
assert_eq!(
captured.display_text(),
"legacy parser rejected `bad-token` from legacy_parser"
);
assert!(captured.debug_text().contains("BorrowedLegacyError"));
assert_eq!(
report.downcast_ref::<SourceTypeName>(),
Some(&SourceTypeName::of::<BorrowedLegacyError<'static>>())
);
}
#[test]
fn test_external_error_by_can_classify_borrowed_legacy_error() {
let report = {
let input = String::from("name with spaces");
let shared = Rc::new(String::from("legacy_parser"));
Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
input: &input,
shared,
})
.into_external_error_by(|error| {
if error.input.contains(' ') {
ErrorKind::InvalidInput
} else {
ErrorKind::Other
}
})
.expect_err("expected public report")
};
assert_eq!(report.current_context(), &ErrorKind::InvalidInput);
assert!(report.contains::<ExternalError>());
assert_eq!(
report.downcast_ref::<SourceTypeName>(),
Some(&SourceTypeName::of::<BorrowedLegacyError<'static>>())
);
}
#[test]
fn test_external_typed_by_keeps_snapshot_and_new_typed_context() {
let report = {
let input = String::from("bad-token");
let shared = Rc::new(String::from("legacy_parser"));
Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
input: &input,
shared,
})
.into_external_typed_by(|_| ExternalContext::LegacyParse)
.expect_err("expected typed report")
};
assert_eq!(report.current_context(), &ExternalContext::LegacyParse);
assert!(report.contains::<ExternalError>());
assert_eq!(
report.downcast_ref::<SourceTypeName>(),
Some(&SourceTypeName::of::<BorrowedLegacyError<'static>>())
);
}
#[test]
fn test_external_error_with_supports_errors_without_display_or_std_error() {
let report = Err::<(), RawForeignCode>(RawForeignCode {
code: 503,
subsystem: "ffi_gateway",
})
.into_external_error_with(|error| {
(
ErrorKind::Dependency,
ExternalError::new(
format!(
"{} rejected request with code {}",
error.subsystem, error.code
),
format!("{error:?}"),
),
)
})
.expect_err("expected public report");
assert_eq!(report.current_context(), &ErrorKind::Dependency);
let captured = report
.downcast_ref::<ExternalError>()
.expect("external snapshot should exist");
assert_eq!(
captured.display_text(),
"ffi_gateway rejected request with code 503"
);
assert!(captured.debug_text().contains("ffi_gateway"));
assert_eq!(
report.downcast_ref::<SourceTypeName>(),
Some(&SourceTypeName::of::<RawForeignCode>())
);
}
#[test]
fn test_external_classified_error_uses_trait_based_mapping_for_non_std_error() {
let report = {
let input = String::from("bad-token");
let shared = Rc::new(String::from("legacy_parser"));
Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
input: &input,
shared,
})
.into_external_classified_error()
.expect_err("expected public report")
};
assert_eq!(report.current_context(), &ErrorKind::InvalidInput);
assert!(report.contains::<ExternalError>());
}
}