Skip to content

Commit

Permalink
📝CustomErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
nihalxkumar committed May 12, 2024
1 parent 880ce32 commit 12bd64d
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
100 changes: 100 additions & 0 deletions src/Learning-Rust/CustomErrors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Custom Errors

Functions may fail in more than one way

### Error Enumerations

- allows errors to be easily defined.
- can match on different error types.
- prefer using match wherever possible with errors.

### Error Requirements

- must implement the Debug trait
- Displays error info in debug context.
- Display traits.
- Displays error info in user context.
- must implement the Error trait.
- Interoperability with code using dynamic errors.

### Manual Error Creation

```rust, ignore
#[derive(Debug)]
enum LockError {
MechanicalError(i32),
NetworkError,
NotAuthorized,
}
use std::error::Error;
impl Error for LockError {} // will work with default implementation
use std::fmt;
impl fmt::Display for LockError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
LockError::MechanicalError(ref err) => write!(f, "Mechanical error: {}", err),
LockError::NetworkError => write!(f, "Network error"),
LockError::NotAuthorized => write!(f, "Not authorized"),
}
}
}
```

### Using `thiserror` crate

`thiserror` crate provides a procedural macro to derive the Error trait.

```rust, ignore
#[derive(Debug, Error)]
enum LockError {
#[error("Mechanical error: {0}")]
MechanicalError(i32),
#[error("Network error")]
NetworkError,
#[error("Not authorized")]
NotAuthorized,
}
fn lock_door() -> Result<(), LockError> {
// code
Err(LockError::NotAuthorized)
}
```

### Error Conversion

```rust, ignore
use thiserror::Error;
#[derive(Debug, Error)]
enum NetworkError {
#[error("Connection timed out")]
Timeout,
#[error("Connection reset by peer")]
Reset,
#[error("Unreachable")]
Unreachable
}
enum LockError {
#[error("Mechanical error: {0}")]
MechanicalError(i32),
#[error("Network error")]
// type conversion
NetworkError(#[from] NetworkError),
#[error("Not authorized")]
NotAuthorized,
}
```

```admonish note
Never put unrelated error into a single enumeration
changes to the enumeration will cascade across the codebase
```


1 change: 1 addition & 0 deletions src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ This is to document my progress and to share my learnings with others who may fi
- [Memory](./Learning-Rust/memory.md)
- [Trait Objects](./Learning-Rust/trait_objects.md)
- [Lifetimes](./Learning-Rust/lifetimes.md)
- [Custom Errors](./Learning-Rust/CustomErrors.md)
- [Acknowledgements](./Learning-Rust/Acknowledgements.md)
</details>

Expand Down
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
- [Memory](./Learning-Rust/memory.md)
- [Trait Objects](./Learning-Rust/trait_objects.md)
- [Lifetimes](./Learning-Rust/lifetimes.md)
- [Custom Errors](./Learning-Rust/CustomErrors.md)
- [Acknowledgements](./Learning-Rust/Acknowledgements.md)

---
Expand Down

0 comments on commit 12bd64d

Please sign in to comment.