diff --git a/packages/libs/error-stack/Cargo.toml b/packages/libs/error-stack/Cargo.toml index 31456733c74..6cce4c5c862 100644 --- a/packages/libs/error-stack/Cargo.toml +++ b/packages/libs/error-stack/Cargo.toml @@ -46,6 +46,10 @@ required-features = ["hooks"] name = "demo" required-features = ["std"] +[[example]] +name = "exit_code" +required-features = ["std"] + [[example]] name = "parse_config" required-features = ["std"] diff --git a/packages/libs/error-stack/examples/exit_code.rs b/packages/libs/error-stack/examples/exit_code.rs new file mode 100644 index 00000000000..6f8cbb40641 --- /dev/null +++ b/packages/libs/error-stack/examples/exit_code.rs @@ -0,0 +1,24 @@ +//! Example of using `attach` to set a custom exit code. Requires nightly and std feature. + +use std::process::{ExitCode, Termination}; + +use error_stack::{Context, Report}; + +#[derive(Debug)] +struct CustomError; + +impl Context for CustomError {} + +impl std::fmt::Display for CustomError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Custom Error") + } +} + +fn main() -> ExitCode { + let report = Report::new(CustomError) + .attach(ExitCode::from(100)) + .attach_printable("This error has an exit code of 100!"); + + report.report() +} diff --git a/packages/libs/error-stack/src/report.rs b/packages/libs/error-stack/src/report.rs index 60d083a8bbe..c37583385c9 100644 --- a/packages/libs/error-stack/src/report.rs +++ b/packages/libs/error-stack/src/report.rs @@ -2,6 +2,8 @@ use alloc::{boxed::Box, string::ToString, vec::Vec}; use core::{fmt, fmt::Write, marker::PhantomData, panic::Location}; #[cfg(all(nightly, feature = "std"))] use std::backtrace::{Backtrace, BacktraceStatus}; +#[cfg(feature = "std")] +use std::process::ExitCode; #[cfg(feature = "spantrace")] use tracing_error::{SpanTrace, SpanTraceStatus}; @@ -617,6 +619,20 @@ impl fmt::Debug for Report { } } +#[cfg(feature = "std")] +impl std::process::Termination for Report { + fn report(self) -> ExitCode { + #[cfg(not(nightly))] + return ExitCode::FAILURE; + + #[cfg(nightly)] + self.request_ref::() + .next() + .copied() + .unwrap_or(ExitCode::FAILURE) + } +} + pub struct ReportImpl { pub(super) frame: Frame, #[cfg(all(nightly, feature = "std"))]