ffx_command_error/
context.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright 2023 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::Error;
use anyhow::Context;
use errors::{FfxError, IntoExitCode, ResultExt};
use std::fmt::Display;

/// Adds helpers to result types to produce useful error messages to the user from
/// the ffx frontend (through [`crate::Error`])
pub trait FfxContext<T, E> {
    /// Make this error into a BUG check that will display to the user as an error that
    /// shouldn't happen.
    fn bug(self) -> Result<T, Error>;

    /// Make this error into a BUG check that will display to the user as an error that
    /// shouldn't happen, with the added context.
    fn bug_context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error>;

    /// Make this error into a BUG check that will display to the user as an error that
    /// shouldn't happen, with the added context returned by the closure `f`.
    fn with_bug_context<C: Display + Send + Sync + 'static>(
        self,
        f: impl FnOnce() -> C,
    ) -> Result<T, Error>;

    /// Make this error into a displayed user error, with the added context for display to the user.
    /// Use this for errors that happen in the normal course of execution, like files not being found.
    fn user_message<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error>;

    /// Make this error into a displayed user error, with the added context for display to the user.
    /// Use this for errors that happen in the normal course of execution, like files not being found.
    fn with_user_message<C: Display + Send + Sync + 'static>(
        self,
        f: impl FnOnce() -> C,
    ) -> Result<T, Error>;
}

impl<T, E> FfxContext<T, E> for Result<T, E>
where
    Self: anyhow::Context<T, E>,
    E: Into<anyhow::Error>,
{
    fn bug(self) -> Result<T, Error> {
        self.map_err(|e| Error::Unexpected(e.into()))
    }

    fn bug_context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error> {
        self.context(context).map_err(Error::Unexpected)
    }

    fn with_bug_context<C: Display + Send + Sync + 'static>(
        self,
        f: impl FnOnce() -> C,
    ) -> Result<T, Error> {
        self.with_context(f).map_err(Error::Unexpected)
    }

    fn user_message<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error> {
        self.context(context).map_err(Error::User)
    }

    fn with_user_message<C: Display + Send + Sync + 'static>(
        self,
        f: impl FnOnce() -> C,
    ) -> Result<T, Error> {
        self.with_context(f).map_err(Error::User)
    }
}

impl<T> FfxContext<T, core::convert::Infallible> for Option<T>
where
    Self: anyhow::Context<T, core::convert::Infallible>,
{
    fn bug(self) -> Result<T, Error> {
        self.ok_or_else(|| Error::Unexpected(anyhow::anyhow!("Option is None")))
    }

    fn bug_context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error> {
        self.context(context).map_err(Error::Unexpected)
    }

    fn with_bug_context<C: Display + Send + Sync + 'static>(
        self,
        f: impl FnOnce() -> C,
    ) -> Result<T, Error> {
        self.with_context(f).map_err(Error::Unexpected)
    }

    fn user_message<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error> {
        self.context(context).map_err(Error::User)
    }

    fn with_user_message<C: Display + Send + Sync + 'static>(
        self,
        f: impl FnOnce() -> C,
    ) -> Result<T, Error> {
        self.with_context(f).map_err(Error::User)
    }
}

impl ResultExt for Error {
    fn ffx_error<'a>(&'a self) -> Option<&'a FfxError> {
        match self {
            Error::User(err) => err.downcast_ref(),
            _ => None,
        }
    }
}
impl IntoExitCode for Error {
    fn exit_code(&self) -> i32 {
        use Error::*;
        match self {
            Help { code, .. } | ExitWithCode(code) => *code,
            Unexpected(err) | User(err) | Config(err) => {
                err.ffx_error().map(FfxError::exit_code).unwrap_or(1)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::*;
    use anyhow::anyhow;
    use assert_matches::assert_matches;

    #[test]
    fn error_context_helpers() {
        assert_matches!(
            anyhow::Result::<()>::Err(anyhow!(ERR_STR)).bug(),
            Err(Error::Unexpected(_)),
            "anyhow.bug() should be a bugcheck error"
        );
        assert_matches!(
            anyhow::Result::<()>::Err(anyhow!(ERR_STR)).bug_context("boom"),
            Err(Error::Unexpected(_)),
            "anyhow.bug_context() should be a bugcheck error"
        );
        assert_matches!(
            anyhow::Result::<()>::Err(anyhow!(ERR_STR)).with_bug_context(|| "boom"),
            Err(Error::Unexpected(_)),
            "anyhow.bug_context() should be a bugcheck error"
        );
        assert_matches!(anyhow::Result::<()>::Err(anyhow!(ERR_STR)).bug_context(FfxError::TestingError), Err(Error::Unexpected(_)), "anyhow.bug_context() should create a bugcheck error even if given an ffx error (magic reduction)");
        assert_matches!(
            anyhow::Result::<()>::Err(anyhow!(ERR_STR)).user_message("boom"),
            Err(Error::User(_)),
            "anyhow.user_message() should be a user error"
        );
        assert_matches!(
            anyhow::Result::<()>::Err(anyhow!(ERR_STR)).with_user_message(|| "boom"),
            Err(Error::User(_)),
            "anyhow.with_user_message() should be a user error"
        );
        assert_matches!(anyhow::Result::<()>::Err(anyhow!(ERR_STR)).with_user_message(|| FfxError::TestingError).ffx_error(), Some(FfxError::TestingError), "anyhow.with_user_message should be a user error that properly extracts to the ffx error.");
    }
}