Skip to content

Improved Error Handling#74

Merged
MusicalNinjaDad merged 14 commits into
mainfrom
ErrCodes
Oct 29, 2025
Merged

Improved Error Handling#74
MusicalNinjaDad merged 14 commits into
mainfrom
ErrCodes

Conversation

@MusicalNinjaDad

@MusicalNinjaDad MusicalNinjaDad commented Oct 29, 2025

Copy link
Copy Markdown
Owner

Summary by Sourcery

Introduce structured error handling and improve CLI error reporting by wrapping ELF parsing errors in SnaggleError, returning InvocationError for invalid recursive usage, and implementing custom argument validation with ExactArgs. Update main to silence usage on error, initialize help/version flags, and distinguish exit codes for SnaggleError vs other errors. Revise ELF error formatting and synchronize tests with the new error types and message formats.

New Features:

  • Add SnaggleError and InvocationError types for structured error encapsulation
  • Implement custom ExactArgs function for detailed argument count validation

Enhancements:

  • Wrap elf.New errors in SnaggleError and return InvocationError for recursive flag on non-directory targets
  • Configure Cobra CLI to silence usage on error, initialize default help/version flags, and handle errors with specific exit codes and usage output
  • Simplify ELF error messages by removing the redundant "error(s)" prefix

Tests:

  • Revise CLI tests to assert empty stdout and exact stderr messages and exit codes for invalid arguments, panics, invalid ELF files, and recursive flags
  • Add new CLI and library tests for invalid ELF parsing and --recursive on files, checking structured error types and captured log output
  • Update unit tests in the elf package to match the updated error message formatting

@MusicalNinjaDad MusicalNinjaDad linked an issue Oct 29, 2025 that may be closed by this pull request
@sourcery-ai

sourcery-ai Bot commented Oct 29, 2025

Copy link
Copy Markdown

Reviewer's Guide

This PR overhauls error handling both in the library and CLI by introducing custom error types for wrapping, refining Cobra argument validation with a custom ExactArgs function, updating main’s error dispatch logic, and expanding and refactoring tests to assert precise stdout/stderr behavior—including new invalid ELF and recursive-file scenarios. ELF parsing error messages are also simplified.

Sequence diagram for main error dispatch logic in CLI

sequenceDiagram
    participant main
    participant rootCmd
    participant os
    participant snaggleError
    main->>rootCmd: Execute()
    alt err == nil
        main->>os: Exit(0)
    else errors.As(err, &snaggleError)
        main->>os: Exit(1)
    else
        main->>rootCmd: UsageString()
        main->>os: Exit(2)
    end
Loading

Class diagram for new and updated error types

classDiagram
    class SnaggleError {
        +string Src
        +string Dst
        +error err
        +Error() string
        +Unwrap() error
    }
    class InvocationError {
        +string Path
        +string Target
        +error err
        +Error() string
        +Unwrap() error
    }
    SnaggleError --|> error
    InvocationError --|> error
Loading

Class diagram for updated argument validation in CLI

classDiagram
    class cobra_Command {
        +Use string
        +SilenceUsage bool
        +DisableFlagsInUseLine bool
        +Long string
        +Args PositionalArgs
        +RunE func(cmd, args) error
    }
    class ExactArgs {
        +ExactArgs(n int) cobra.PositionalArgs
    }
    cobra_Command --> ExactArgs: uses
Loading

File-Level Changes

Change Details Files
Introduced custom error types and updated error wrapping
  • Added SnaggleError and InvocationError types with Error() and Unwrap() methods
  • Wrapped underlying errors in Snaggle() and in recursive invocation path
  • Updated main error switch to use errors.As on SnaggleError
snaggle.go
snaggle/main.go
Replaced cobra.ExactArgs with custom ExactArgs and improved CLI flag initialization
  • Implemented ExactArgs() for argument count validation
  • Replaced cobra.ExactArgs with ExactArgs in rootCmd.Args
  • Initialized default help/version flags and set SilenceUsage
snaggle/main.go
Refactored CLI tests for strict error output assertions
  • Captured stdout/stderr via exec.Command.Output and asserted empty stdout
  • Built expectedErr strings and compared stderr exactly for exit codes 1–3
  • Added new TestInvalidElf and TestRecurseFile cases to cover parsing and directory errors
snaggle/cli_test.go
Refactored library tests to assert error types and capture logs
  • Redirected log output to a buffer and reset between runs
  • Used assert.ErrorAs to check for specific SnaggleError and InvocationError types
  • Removed old iter/slices patterns in favor of direct comparisons
snaggle_test.go
Simplified ELF parsing error messages
  • Changed ErrElf.Error prefix from “error(s) parsing” to “parsing”
  • Updated elf_errors_test.go assertions to match new message format
elf/elf.go
elf/elf_errors_test.go
Added test data for invalid ELF scenarios
  • Defined commonElfs["ldd"] entry with bad magic number
  • Added Ldd binaryDetails for invalid ELF tests
internal/testing/testdata.go

Assessment against linked issues

Issue Objective Addressed Explanation
#73 Implement a dedicated SnaggleError type for error handling in the CLI, and use errors.As to detect it for exit code logic.
#73 Update main.go to use errors.As to check for SnaggleError and set exit code 1 when encountered.
#73 Remove the previous string-matching logic for exit code 2 and ensure exit codes are set according to error type (SnaggleError: 1, invalid command: 2, panic: 3).

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@MusicalNinjaDad MusicalNinjaDad linked an issue Oct 29, 2025 that may be closed by this pull request
@codecov

codecov Bot commented Oct 29, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 48.27586% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.11%. Comparing base (9053452) to head (9aae553).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
snaggle/main.go 25.00% 8 Missing and 1 partial ⚠️
snaggle.go 62.50% 5 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #74      +/-   ##
==========================================
- Coverage   75.36%   74.11%   -1.26%     
==========================================
  Files           8        8              
  Lines         483      506      +23     
==========================================
+ Hits          364      375      +11     
- Misses         85       95      +10     
- Partials       34       36       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Extract the repetitive CLI test setup and exit‐code/assertion logic into shared helper functions to reduce duplication and improve readability.
  • In main.go the usage text is printed via println (stdout)—consider using PrintErr or fmt.Fprintln(os.Stderr, ...) so usage and errors go to stderr consistently.
  • To make error matching with errors.Is more ergonomic, consider adding an Is method on InvocationError and SnaggleError or otherwise supporting error.Is in addition to errors.As.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Extract the repetitive CLI test setup and exit‐code/assertion logic into shared helper functions to reduce duplication and improve readability.
- In main.go the usage text is printed via println (stdout)—consider using PrintErr or fmt.Fprintln(os.Stderr, ...) so usage and errors go to stderr consistently.
- To make error matching with errors.Is more ergonomic, consider adding an Is method on InvocationError and SnaggleError or otherwise supporting error.Is in addition to errors.As.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@MusicalNinjaDad MusicalNinjaDad merged commit 58615fb into main Oct 29, 2025
10 of 12 checks passed
@MusicalNinjaDad MusicalNinjaDad deleted the ErrCodes branch October 29, 2025 17:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Snaggle Error type & exit code logic Exit(2) on snaggle --recursive FILENAME

1 participant