Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Termination for error_stack::Report #671

Merged
merged 7 commits into from
Jun 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/libs/error-stack/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
24 changes: 24 additions & 0 deletions packages/libs/error-stack/examples/exit_code.rs
Original file line number Diff line number Diff line change
@@ -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()
}
16 changes: 16 additions & 0 deletions packages/libs/error-stack/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -617,6 +619,20 @@ impl<Context> fmt::Debug for Report<Context> {
}
}

#[cfg(feature = "std")]
impl<Context> std::process::Termination for Report<Context> {
fn report(self) -> ExitCode {
#[cfg(not(nightly))]
return ExitCode::FAILURE;

#[cfg(nightly)]
self.request_ref::<ExitCode>()
.next()
.copied()
.unwrap_or(ExitCode::FAILURE)
}
}

pub struct ReportImpl {
pub(super) frame: Frame,
#[cfg(all(nightly, feature = "std"))]
Expand Down