Repository navigation
refactor(sns-cli): Use anyhow - #1120
Merged
Merged
Conversation
anchpop
force-pushed
the
@anchpop/use-anyhow-in-sns-cli
branch
from
August 23, 2024 20:44
4f0a33a to
7b7fd35
Compare
anchpop
force-pushed
the
@anchpop/use-anyhow-in-sns-cli
branch
3 times, most recently
from
August 23, 2024 21:16
f4a1b78 to
9b56cd0
Compare
anchpop
force-pushed
the
@anchpop/use-anyhow-in-sns-cli
branch
from
August 23, 2024 21:53
9b56cd0 to
8a1535c
Compare
max-dfinity
approved these changes
Aug 23, 2024
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
It is generally not a very good practice to perform an
.unwrap()that might plausibly fail, outside of tests. Instead, it is better to return an error. Even in themainfunction, you can return aResultinstead of using.unwrap()orexit(1)(and returning anErrfrom the main function will automatically set a non-zero exit code). Usingexit(1)is particularly dangerous as you may forget to call it, or forget to useeprintln!instead ofprintln!, in both cases doing something somewhat unexpected that the compiler will not warn you about.Solution
Convert all the sns-cli endpoints to return an
anyhow::Resultinstead of(). This enables them to return errors instead of panicking.Impoved code
Example 1
Using anyhow makes some of our code a bit more concise as well. For example, compare the original:
with:
Which is not exactly equivalent, but the latter returns a (imho) nicer error message. For the unfamiliar,
outputs:
Using
.context()gives us something that's almost like a human-readable backtrace:outputs:
Example 2
Becomes
Additional notes
I have not actually removed all the occurrences of
.unwrap()yet, but I have updated all the cases where we calledexit(1).