R中值[[3L]](cond)的误差是多少?

sop*_*sop 9 error-handling r try-catch

由于内存不足,我有一个错误的代码.实际上我在大数据上做了一个线性模型(lm).问题不是因为它给了我错误,我想记录,但因为它包含value[[3L]](cond).

我的错误看起来像这样:

Error in value[[3L]](cond): While training model Error: cannot allocate vector of size 6.4 Gb
Run Code Online (Sandbox Code Playgroud)

记录它的代码看起来像这样(使用logging lib):

tryCatch({
  # some code
  tryCatch({
    # some other code
  }, warning = function(war){
    logwarn(war, logger = "MyLogger")
  }, error = function(err){
    stop(paste("While training model", err, sep = " "))
  })
  some more code
}, error = function(err){
  logerror(err, logger = "MyLogger")
})
Run Code Online (Sandbox Code Playgroud)

我的问题是它为什么这么说Error in value[[3L]](cond):?我做错了,我不知道是不是错了?不应该只是Error: <error message>吗?

Jth*_*rpe 6

在发生错误条件时,您stop()在内部tryCatch和内部发出,tryCatch()调用您提供的错误处理程序,这是列表中的第三个元素(内部tryCatch).它调用该处理程序传递条件cond通过:value[[3L]](cond).由于您的错误处理程序调用停止,因此这是调用最新错误的位置.

您可以使用traceback()(隐式调用print())在错误处理程序中查看调用堆栈,如下所示:

tryCatch({
    stop('')
},error=function(err){
    traceback()
})
Run Code Online (Sandbox Code Playgroud)

产量:

5: print(where) at #4
4: value[[3L]](cond)
3: tryCatchOne(expr, names, parentenv, handlers[[1L]])
2: tryCatchList(expr, classes, parentenv, handlers)
1: tryCatch({
       stop()
   }, error = function(err) {
       print(where)
   })
Run Code Online (Sandbox Code Playgroud)

如果您希望保留原始错误的调用堆栈但有更多信息性错误消息,只需编辑错误并重新提升它:

  tryCatch({
    # some other code
  }, warning = function(war){
    logwarn(war, logger = "MyLogger")
  }, error = function(err){
    # edit the error message
    err$message <- paste("While training model", err, sep = " ")
    # and re-raise
    stop(err)
  })
Run Code Online (Sandbox Code Playgroud)