Skip to content

Commit

Permalink
attributes: fix #[instrument(err)] in case of early returns (#1006)
Browse files Browse the repository at this point in the history
## Motivation

For the non-async case, early returns could escape the block so that the
error handling was skipped.

I was wondering for quite some time now what was going on here 😆

## Solution

Just put the block into the all-mighty "try-catch-closure" construct.

Annotating the return type of the closure improves the error message in
case of a mismatch between the function's return type and body.

Example code:
```
fn with_err() -> Result<(), String> {
    Ok(5)
}
```

Without return type annotation:
```
error[E0308]: mismatched types
 --> src/main.rs:2:37
  |
2 |   fn with_err() -> Result<(), String> {
  |  _____________________________________^
3 | |     Ok(5)
4 | | }
  | |_^ expected `()`, found integer
```

With return type annotation:
```
error[E0308]: mismatched types
 --> src/main.rs:3:8
  |
3 |     Ok(5)
  |        ^ expected `()`, found integer
```
  • Loading branch information
Nilix007 authored Oct 7, 2020
1 parent 940808c commit 4e87df5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion tracing-attributes/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,8 @@ fn gen_body(
quote_spanned!(block.span()=>
let __tracing_attr_span = #span;
let __tracing_attr_guard = __tracing_attr_span.enter();
match { #block } {
let f = move || #return_type { #block };
match f() {
Ok(x) => Ok(x),
Err(e) => {
tracing::error!(error = %e);
Expand Down
21 changes: 21 additions & 0 deletions tracing-attributes/tests/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,27 @@ fn test() {
handle.assert_finished();
}

#[instrument(err)]
fn err_early_return() -> Result<u8, TryFromIntError> {
u8::try_from(1234)?;
Ok(5)
}

#[test]
fn test_early_return() {
let span = span::mock().named("err_early_return");
let (subscriber, handle) = subscriber::mock()
.new_span(span.clone())
.enter(span.clone())
.event(event::mock().at_level(Level::ERROR))
.exit(span.clone())
.drop_span(span)
.done()
.run_with_handle();
with_default(subscriber, || err_early_return().ok());
handle.assert_finished();
}

#[instrument(err)]
async fn err_async(polls: usize) -> Result<u8, TryFromIntError> {
let future = PollN::new_ok(polls);
Expand Down

0 comments on commit 4e87df5

Please sign in to comment.