Skip to content

Commit 247e27a

Browse files
authored
feat(error): add structured exit codes for scriptable error handling (#428)
* feat(error): add structured exit codes for scriptable error handling Replace the hardcoded `std::process::exit(1)` with a type-specific exit code derived from the GwsError variant: 0 — success 1 — API error (GwsError::Api) 2 — auth error (GwsError::Auth) 3 — validation (GwsError::Validation) 4 — discovery (GwsError::Discovery) 5 — internal (GwsError::Other) This allows shell scripts to branch on failure type without parsing the JSON error output: gws drive files list ... case $? in 1) echo "API error — check your params" ;; 2) echo "Auth error — run: gws auth login" ;; 3) echo "Bad arguments" ;; esac Changes: - Add GwsError::exit_code() mapping variants to codes - Update main() to call std::process::exit(err.exit_code()) - Document exit codes in gws --help (print_usage) - Document exit codes in README under new Exit Codes section - Add 6 unit tests including a regression guard asserting all codes are distinct * refactor(error): replace magic exit-code numbers with named constants Add EXIT_CODE_API/AUTH/VALIDATION/DISCOVERY/OTHER associated constants on GwsError so callers and tests reference symbolic names rather than bare integers. Update exit_code() match arms and all tests accordingly. The distinctness test now validates the constants array directly. Addresses code-review feedback requesting named constants. * refactor(error): centralize exit code help text via EXIT_CODE_DOCUMENTATION Add a module-level EXIT_CODE_DOCUMENTATION constant — a static slice of (code, description) pairs built from the EXIT_CODE_* constants. Replace the hardcoded println! block in print_usage() with a loop over this slice so the help output is always in sync with the defined constants and cannot drift out of date. Addresses code-review feedback requesting a single source of truth.
1 parent 087066f commit 247e27a

4 files changed

Lines changed: 147 additions & 1 deletion

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
"@googleworkspace/cli": minor
3+
---
4+
5+
Add structured exit codes for scriptable error handling
6+
7+
`gws` now exits with a type-specific code instead of always using `1`:
8+
9+
| Code | Meaning |
10+
|------|---------|
11+
| `0` | Success |
12+
| `1` | API error — Google returned a 4xx/5xx response |
13+
| `2` | Auth error — credentials missing, expired, or invalid |
14+
| `3` | Validation error — bad arguments, unknown service, invalid flag |
15+
| `4` | Discovery error — could not fetch the API schema document |
16+
| `5` | Internal error — unexpected failure |
17+
18+
Exit codes are documented in `gws --help` and in the README.

‎README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ npm install -g @googleworkspace/cli
3333
- [AI Agent Skills](#ai-agent-skills)
3434
- [Advanced Usage](#advanced-usage)
3535
- [Environment Variables](#environment-variables)
36+
- [Exit Codes](#exit-codes)
3637
- [Architecture](#architecture)
3738
- [Troubleshooting](#troubleshooting)
3839
- [Development](#development)
@@ -317,6 +318,27 @@ All variables are optional. See [`.env.example`](.env.example) for a copy-paste
317318
318319
Environment variables can also be set in a `.env` file (loaded via [dotenvy](https://crates.io/crates/dotenvy)).
319320
321+
## Exit Codes
322+
323+
`gws` uses structured exit codes so scripts can branch on the failure type without parsing error output.
324+
325+
| Code | Meaning | Example cause |
326+
|------|---------|---------------|
327+
| `0` | Success | Command completed normally |
328+
| `1` | API error | Google returned a 4xx/5xx response |
329+
| `2` | Auth error | Credentials missing, expired, or invalid |
330+
| `3` | Validation error | Bad arguments, unknown service, invalid flag |
331+
| `4` | Discovery error | Could not fetch the API schema document |
332+
| `5` | Internal error | Unexpected failure |
333+
334+
```bash
335+
gws drive files list --params '{"fileId": "bad"}'
336+
echo $? # 1 — API error
337+
338+
gws unknown-service files list
339+
echo $? # 3 — validation error (unknown service)
340+
```
341+
320342
## Architecture
321343
322344
`gws` uses a **two-phase parsing** strategy:

‎src/error.rs‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,51 @@ pub enum GwsError {
3939
Other(#[from] anyhow::Error),
4040
}
4141

42+
/// Human-readable exit code table, keyed by (code, description).
43+
///
44+
/// Used by `print_usage()` so the help text stays in sync with the
45+
/// constants defined below without requiring manual updates in two places.
46+
pub const EXIT_CODE_DOCUMENTATION: &[(i32, &str)] = &[
47+
(0, "Success"),
48+
(GwsError::EXIT_CODE_API, "API error — Google returned an error response"),
49+
(GwsError::EXIT_CODE_AUTH, "Auth error — credentials missing or invalid"),
50+
(GwsError::EXIT_CODE_VALIDATION, "Validation — bad arguments or input"),
51+
(GwsError::EXIT_CODE_DISCOVERY, "Discovery — could not fetch API schema"),
52+
(GwsError::EXIT_CODE_OTHER, "Internal — unexpected failure"),
53+
];
54+
4255
impl GwsError {
56+
/// Exit code for [`GwsError::Api`] variants.
57+
pub const EXIT_CODE_API: i32 = 1;
58+
/// Exit code for [`GwsError::Auth`] variants.
59+
pub const EXIT_CODE_AUTH: i32 = 2;
60+
/// Exit code for [`GwsError::Validation`] variants.
61+
pub const EXIT_CODE_VALIDATION: i32 = 3;
62+
/// Exit code for [`GwsError::Discovery`] variants.
63+
pub const EXIT_CODE_DISCOVERY: i32 = 4;
64+
/// Exit code for [`GwsError::Other`] variants.
65+
pub const EXIT_CODE_OTHER: i32 = 5;
66+
67+
/// Map each error variant to a stable, documented exit code.
68+
///
69+
/// | Code | Meaning |
70+
/// |------|----------------------------------------------|
71+
/// | 0 | Success (never returned here) |
72+
/// | 1 | API error — Google returned an error response |
73+
/// | 2 | Auth error — credentials missing or invalid |
74+
/// | 3 | Validation error — bad arguments or input |
75+
/// | 4 | Discovery error — could not fetch API schema |
76+
/// | 5 | Internal error — unexpected failure |
77+
pub fn exit_code(&self) -> i32 {
78+
match self {
79+
GwsError::Api { .. } => Self::EXIT_CODE_API,
80+
GwsError::Auth(_) => Self::EXIT_CODE_AUTH,
81+
GwsError::Validation(_) => Self::EXIT_CODE_VALIDATION,
82+
GwsError::Discovery(_) => Self::EXIT_CODE_DISCOVERY,
83+
GwsError::Other(_) => Self::EXIT_CODE_OTHER,
84+
}
85+
}
86+
4387
pub fn to_json(&self) -> serde_json::Value {
4488
match self {
4589
GwsError::Api {
@@ -126,6 +170,63 @@ pub fn print_error_json(err: &GwsError) {
126170
mod tests {
127171
use super::*;
128172

173+
#[test]
174+
fn test_exit_code_api() {
175+
let err = GwsError::Api {
176+
code: 404,
177+
message: "Not Found".to_string(),
178+
reason: "notFound".to_string(),
179+
enable_url: None,
180+
};
181+
assert_eq!(err.exit_code(), GwsError::EXIT_CODE_API);
182+
}
183+
184+
#[test]
185+
fn test_exit_code_auth() {
186+
assert_eq!(
187+
GwsError::Auth("bad token".to_string()).exit_code(),
188+
GwsError::EXIT_CODE_AUTH
189+
);
190+
}
191+
192+
#[test]
193+
fn test_exit_code_validation() {
194+
assert_eq!(
195+
GwsError::Validation("missing arg".to_string()).exit_code(),
196+
GwsError::EXIT_CODE_VALIDATION
197+
);
198+
}
199+
200+
#[test]
201+
fn test_exit_code_discovery() {
202+
assert_eq!(
203+
GwsError::Discovery("fetch failed".to_string()).exit_code(),
204+
GwsError::EXIT_CODE_DISCOVERY
205+
);
206+
}
207+
208+
#[test]
209+
fn test_exit_code_other() {
210+
assert_eq!(
211+
GwsError::Other(anyhow::anyhow!("oops")).exit_code(),
212+
GwsError::EXIT_CODE_OTHER
213+
);
214+
}
215+
216+
#[test]
217+
fn test_exit_codes_are_distinct() {
218+
// Ensure all named constants are unique (regression guard).
219+
let codes = [
220+
GwsError::EXIT_CODE_API,
221+
GwsError::EXIT_CODE_AUTH,
222+
GwsError::EXIT_CODE_VALIDATION,
223+
GwsError::EXIT_CODE_DISCOVERY,
224+
GwsError::EXIT_CODE_OTHER,
225+
];
226+
let unique: std::collections::HashSet<i32> = codes.iter().copied().collect();
227+
assert_eq!(unique.len(), codes.len(), "exit codes must be distinct: {codes:?}");
228+
}
229+
129230
#[test]
130231
fn test_error_to_json_api() {
131232
let err = GwsError::Api {

‎src/main.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ async fn main() {
4949

5050
if let Err(err) = run().await {
5151
print_error_json(&err);
52-
std::process::exit(1);
52+
std::process::exit(err.exit_code());
5353
}
5454
}
5555

@@ -460,6 +460,11 @@ fn print_usage() {
460460
" GOOGLE_WORKSPACE_PROJECT_ID Override the GCP project ID for quota and billing"
461461
);
462462
println!();
463+
println!("EXIT CODES:");
464+
for (code, description) in crate::error::EXIT_CODE_DOCUMENTATION {
465+
println!(" {:<5}{}", code, description);
466+
}
467+
println!();
463468
println!("COMMUNITY:");
464469
println!(" Star the repo: https://github.com/googleworkspace/cli");
465470
println!(" Report bugs / request features: https://github.com/googleworkspace/cli/issues");

0 commit comments

Comments
 (0)