r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
498 stars 136 forks source link

`rlang::is_error` false negative (?) #1615

Closed AEBilgrau closed 1 year ago

AEBilgrau commented 1 year ago

Contrary to what I expected, I get the following:

> rlang::is_error(try(log("a"), TRUE))
[1] FALSE

The reason is dead-simple (try returns errors of "try-error" class). I'd be happy provide a fix unless there's a deeper reason for this behavior.

lionel- commented 1 year ago

That's because a "try-error" object is not an error object. It doesn't inherit from "error" or from "condition", and so doesn't implement the condition interface:

out <- try(stop("foo"), silent = TRUE)

conditionMessage(out)
#> Error in `UseMethod()`:
#> ! no applicable method for 'conditionMessage' applied to an object of class "try-error"
#> Run `rlang::last_trace()` to see where the error occurred.

conditionCall(out)
#> Error in `UseMethod()`:
#> ! no applicable method for 'conditionCall' applied to an object of class "try-error"
#> Run `rlang::last_trace()` to see where the error occurred.

The real error object is attached as an attribute:

cnd <- attr(out, "condition")

conditionMessage(cnd)
#> [1] "foo"

conditionCall(cnd)
#> doTryCatch(return(expr), name, parentenv, handler)