【问题标题】:Adding more details after an error message in R在 R 中出现错误消息后添加更多详细信息
【发布时间】:2014-12-22 07:22:27
【问题描述】:

我有一个类似于下面的函数,在循环中创建矩阵。

foo <- function(x, y, z) {
  out <- list(a1 = NULL, a2 = NULL, a3 = NULL)
  for (i in 1:3) {
    t <- 100 * i
    a <- matrix(x, y + t, z)
    out[[i]] <- t(a)
  }
  return(out)
}

以下运行良好。 p

但以下给出cannot allocate vector of length 错误

q <- foo(NA, 3500000, 50)

我想在我的函数中出现的cannot allocate vector of lengthtoo many elements specified 错误之后添加一些额外的message,例如adjust arguments 'y' and 'z'

我正在尝试trytryCatch,但当错误发生在循环中时,似乎无法获得预期的结果。如何做到这一点?

【问题讨论】:

  • trytryCatch 代码你试过了吗?你能指定这个测试的精确“期望结果”是什么吗?
  • 如果函数以Error: cannot allocate vector of sizetoo many elements specified 停止,请提供附加消息adjust arguments 'y' and 'z'

标签: r error-handling try-catch


【解决方案1】:

您可以使用简单的装饰器模式来丰富错误消息:

safify <- function(f){
    function(...){
        tryCatch({
            f(...)
        },
        error=function(e){
            msg=conditionMessage(e)
            if(grepl("cannot allocate", msg)){
                msg=paste(msg, " Adjust arguments 'y' and 'z'", sep='.')
                return(msg)
            }
            msg
        })
    }
}

safefoo = safify(foo)

#res=safefoo(NA, 3500000, 50)
#> res
#[1] "cannot allocate vector of size 667.6 Mb. Adjust arguments 'y' and 'z'"

通过这种方式,您可以捕获可能发生的每种类型的错误,并丰富您想要的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多