rust-lang/rust-clippy · error
called `.err().expect()` on a `Result` value
Error message
called `.err().expect()` on a `Result` value
What it means
Clippy lint ERR_EXPECT: calling .err() on a Result<T, E> converts it into an Option<E>, discarding the Ok(T) payload; .expect(msg) on that Option then panics with the caller-supplied message whenever the Result was Ok. The panic therefore fires on success and reports a misleading generic message instead of the actual value. The lint only fires when T: Debug (so expect_err is expressible) and the MSRV supports EXPECT_ERR.
Solutions
- Replace .err().expect("...") with .expect_err("...") so the panic message includes the debug-printed Ok value
- Use .unwrap_err() when no custom message is needed
- Handle both cases explicitly with a match or if let! to avoid panicking entirely
Defensive patterns
Strategy: type-guard
When it happens
Trigger: Thrown at clippy_lints/src/methods/err_expect.rs:30 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of rust-lang/rust-clippy@13aece1138 (2026-09-07).
Data as JSON: /api/errors/879fcb31541e15eb.
Report an issue: GitHub.
Appendix: source
Thrown at clippy_lints/src/methods/err_expect.rs:30
cx: &LateContext<'_>,
_expr: &rustc_hir::Expr<'_>,
recv: &rustc_hir::Expr<'_>,
expect_span: Span,
err_span: Span,
msrv: Msrv,
) {
let result_ty = cx.typeck_results().expr_ty(recv);
// Grabs the `Result<T, E>` type
if let Some(data_type) = get_data_type(cx, result_ty)
// Tests if the T type in a `Result<T, E>` implements Debug
&& has_debug_impl(cx, data_type)
&& msrv.meets(cx, msrvs::EXPECT_ERR)
{
span_lint_and_sugg(
cx,
ERR_EXPECT,
err_span.to(expect_span),
"called `.err().expect()` on a `Result` value",
"try",
"expect_err".to_string(),
Applicability::MachineApplicable,
);
}
}
/// Given a `Result<T, E>` type, return its data (`T`).
fn get_data_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
match ty.kind() {
ty::Adt(adt, args) if cx.tcx.is_diagnostic_item(sym::Result, adt.did()) => args.types().next(),
_ => None,
}
}
View on GitHub (pinned to 13aece1138)