thistermination
thistermination is a library crate inspired by thiserror to add the std::process::Termination trait to error enums.
[]
= "1.0"
Compiler support: requires rustc 1.56+
Why Implement The Termination Trait?
A struct or enum that implements the std::process::Termination and std::fmt::Debug traits can be returned by the main function, allowing developers to print a message on program exit and set the exit code.
Usage
To add the std::process::Termination trait to an enum, you can use one of three possible derive macros:
-
#[derive(Termination)]: is intended to be used in combination with thiserror, this macro implements the traitsstd::process::Terminationandstd::fmt::Debug. Theexit_codedefaults tolibc::EXIT_FAILURE, and the Debug message is the same as the Display message unless explicitly set usingexit_codeandmsg.use ; use Error; -
#[derive(TerminationFull)]: is intended to be used without thiserror, this macro implements the traitsstd::process::Termination,std::fmt::Debug,std::fmt::Display, andstd::error::Error. Theexit_codedefaults tolibc::EXIT_FAILURE, andmsgis required and used for both Display and Debug.use ; -
#[derive(TerminationNoDebug)]: is the most basic variant, implementing only thestd::process::Terminationtrait. If noexit_codeis provided, it defaults tolibc::EXIT_FAILURE. However, thestd::fmt::Debugtrait is necessary for the enum to be returned by themainfunction and must be implemented manually or using the Debug macro.use ;
Details
-
thistermination does not appear in your public API; the macros simply implement the the various traits.
-
The macros can be derived for unit enums, enums with named fields, and enum tuples.
-
msgsupports accessing the fields of the enum in a format string manner#[termination(msg("{var}"))]⟶write!("{}", self.var)#[termination(msg("{0}"))]⟶write!("{}", self.0)#[termination(msg("{var:?}"))]⟶write!("{:?}", self.var)#[termination(msg("{0:?}"))]⟶write!("{:?}", self.0)
You can also specify additional format string arguments for
msg -
Using
#[from]will generate astd::convert::Fromimplementation for the specific variant. A variant with#[from]is not allowed to contain any additional fields and can only be used in combination with#[derive(TerminationFull)]. -
You can also change the default values of
exit_codeandmsgby adding the#[termination(...)]helper attribute to the enum itself.
Comparison To thiserror
#[derive(TerminationFull)] can be used instead of thiserror as it offers many of the basic features of thiserror. However, it lacks some features like #[source], #[backtrace], the ability to automatically detect a backtrace, and #[error(transparent)]. If any of these features are required, you can use thiserror in combination with #[derive(Termination)].