-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor/improve error handling #48
refactor/improve error handling #48
Conversation
@@ -5,6 +5,7 @@ export RUST_BACKTRACE := "1" | |||
install_tools: | |||
cargo install sqlx-cli | |||
cargo install cargo-pretty-test | |||
cargo install cargo-watch |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Like the name suggests, it allows to autoreload the app in dev when the source code changes
allow-unwrap-in-tests = true | ||
allow-expect-in-tests = true |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We still allow unwrap
and expect
in tests, as we don't need to be "as safe" in them (just like we sometimes use any
in TS tests)
.users | ||
.find(&self.user_id) | ||
.await | ||
.map_err(|_| UseCaseError::InternalError)?; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note this ?
at the end
It allows to return directly the error. This is equivalent to the following
let user = match ctx
.repos
.users
.find(&self.user_id)
.await
.map_err(|_| UseCaseError::InternalError) {
Ok(user) => user,
Err(e) => return Err(e), // Early return in the function
};
Changed
unwrap()
orexpect()
anyhow::Result<T>
Result
reflects thatDetails
Enums
In Rust, there are a few things to keep in mind when handling "errors" and "lack of values (aka null in other languages)"
Rust has 2 enums
Option<T>
, which has 2 values =>Some(T)
orNone
Result<T, E>
, which also has 2 values =>Ok(T)
orErr(E)
So, for example, we can have the following
Unwrap and expect
On there 2 enums, there are quite a few functions that can be used. There are 2 main ones that we need to be careful about
unwrap()
expect()
Regarding
unwrap()
andexpect()
, it does the followingSo, in short,
unwrap()
andexpect()
should be avoided as they make the app to crash.Regarding these 2 enums, it's worth noting that using
?
allows to automatically stop the execution and return theErr(E)
orNone
(but not a panic !).Anyhow
anyhow is a lib that allows to easily forward errors. In the Rust ecosystems, there are 2 main libs used for handling errors
More details in https://google.github.io/comprehensive-rust/error-handling.html (the whole website is a good resource, it's a tutorial from Google's Android team for learning Rust for their own employees
I'll also add some comments in the code in the PR