Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions checkers/rust/avoid_expect.test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
fn test_antipattern() {
let some_option: Option<i32> = None;

// <expect-error>
let _ = some_option.expect("failed to get value");

let some_result: Result<i32, &str> = Err("Error occurred");

// <expect-error>
let _ = some_result.expect("failed to process result");
}

fn test_safe() {
let some_option: Option<i32> = None;

// Safe error handling with unwrap_or
let _ = some_option.unwrap_or(42);

// Safe error handling with match
let _ = match some_option {
Some(val) => val,
None => 0,
};

// Should not flag string literals containing "expect"
let message = "We expect proper error handling in production code.";
}
29 changes: 29 additions & 0 deletions checkers/rust/avoid_expect.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
language: rust
name: avoid_expect
message: "Using expect() can cause runtime panics if an Option is None or Result is Err. Consider handling errors explicitly with match, if let, or the ? operator"
category: antipattern
severity: warning

pattern: |
(
(call_expression
function: (field_expression
value: (_) @variable
field: (field_identifier) @method_name
(#eq? @method_name "expect")
)
arguments: (arguments)
) @avoid_expect
)

exclude:
- "tests/**"
- "vendor/**"
- "**/test_*.rs"
- "**/*_test.rs"

description: |
Using .expect() in Rust can lead to unexpected panics if the value is None (for Option) or Err (for Result).
While expect() provides a custom error message, uncaught panics in production can crash the application.
Consider handling errors explicitly using match or if let, providing defaults with unwrap_or_else(),
or propagating errors using the ? operator.