1use std::fmt::{Display, Formatter, Result as FmtResult};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct ExitRequest(pub i64);
14
15impl Display for ExitRequest {
16 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
17 write!(f, "EXIT requested with code {}", self.0)
18 }
19}
20
21impl std::error::Error for ExitRequest {}
22
23pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
27 err.chain()
28 .find_map(|cause| cause.downcast_ref::<ExitRequest>().map(|exit| exit.0))
29}
30
31#[cfg(test)]
32mod tests {
33 use super::{ExitRequest, exit_code_of};
34
35 #[test]
36 fn display_matches_historic_message() {
37 assert_eq!(ExitRequest(3).to_string(), "EXIT requested with code 3");
38 }
39
40 #[test]
41 fn finds_code_through_context_wrappers() {
42 let err = anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' failed");
43 assert_eq!(exit_code_of(&err), Some(3));
44 }
45
46 #[test]
47 fn none_without_exit() {
48 let err = anyhow::anyhow!("boom").context("wrapped");
49 assert_eq!(exit_code_of(&err), None);
50 }
51}