Home > Software engineering >  How to print an argument of a function when it fails?
How to print an argument of a function when it fails?

Time:12-02

I'm trying to use possibly() to print the argument x as a message when the function sum() fails.

library(purrr)
t <- function(x) {
  p <- possibly(sum, otherwise = message(x))
  p(x)
}

However, I would not expect the below to retrieve any message, since sum() doesn't fail:

> t(1)
1
[1] 1

Instead, the script below works as expected: sum() fails, thus t() prints the message 'a'

> t('a')
a
NULL

CodePudding user response:

As noted in the other answer, possibly simply does something quite different from what you want.

What you want is tryCatch (part of base R):

t <- function(x) {
  tryCatch(sum(x), error = function (.) message(x))
}
t(1)
# [1] 1
t('a')
# a

CodePudding user response:

The argument otherwise of the function purrr::possibly is a value but message(x) is an R expression. According to the documentation:

These functions wrap functions so that instead of generating side effects through printed output, messages, warnings, and errors, they return enhanced output.

  • Related