R: Catch errors and continue execution after logging the stacktrace (no traceback available with tryCatch)

后端 未结 2 1623
心在旅途
心在旅途 2020-12-18 10:09

I have many unattended batch jobs in R running on a server and I have to analyse job failures after they have run.

I am trying to catch errors to log them and recove

2条回答
  •  悲&欢浪女
    2020-12-18 10:34

    The traceback function can be used to print/save the current stack trace, but you have to specify an integer argument, which is the number of stack frames to omit from the top (can be 0). This can be done inside a tryCatch block or anywhere else. Say this is the content of file t.r:

    f <- function() {
        x <- 1
        g()
    }
    g <- function() {
        traceback(0)
    }
    

    When you source this file into R and run f, you get the stack trace:

    3: traceback(0) at t.r#7
    2: g() at t.r#3
    1: f()

    which has file name and line number information for each entry. You will get several stack frames originating from the implementation of tryCatch and you can't skip them by specifying a non-zero argument to traceback, yet indeed this will break in case the implementation of tryCatch changes.

    The file name and line number information (source references) will only be available for code that has been parsed to keep source references (by default the source'd code, but not packages). The stack trace will always have call expressions.

    The stack trace is printed by traceback (no need to call print on it).

    For logging general errors, it is sometimes useful to use options(error=), one then does not need to modify the code that causes the errors.

提交回复
热议问题