失败时如何打印函数的参数?

How to print an argument of a function when it fails?

我正在尝试使用 possibly() 在函数 sum() 失败时将参数 x 作为消息打印出来。

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

但是,我不希望以下内容检索任何消息,因为 sum() 不会失败:

> t(1)
1
[1] 1

相反,下面的脚本按预期工作:sum() 失败,因此 t() 打印消息 'a'

> t('a')
a
NULL

函数 purrr::possibly 的参数 otherwise 是一个值,但 message(x) 是一个 R 表达式。根据文档:

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

如其他答案所述,possibly 只是做了一些与您想要的完全不同的事情。

你要的是tryCatch(基数R的一部分):

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