[Rd] Debugging warnings

Hadley Wickham hadley at rice.edu
Tue May 10 16:35:03 CEST 2011


Hi all,

One thing that's currently a little tricky in R is debugging warnings.
 One solution is to turn them into errors and then use the usual error
tracking mechanisms (e.g. options(error = recover)).  But it should be
possible to use withCallingHandlers to provide more flexibility.  The
function below works, but I'm wondering if there's a more elegant way
to figure out the correct frame to evaluate the action in - I'm
currently counting back one from where warning was called.

on_warning <- function(action, code) {
  q_action <- substitute(action)

  withCallingHandlers(code, warning = function(c) {
    for(i in seq_len(sys.nframe())) {
      f <- as.character(sys.call(i)[[1]])
      if (f == "warning") break;
    }

    eval(q_action, sys.frame(i - 1))
  })
}

x <- 1
f <- function() {
  x <- 2
  g()
}
g <- function() {
  x <- 3
  warning("Leaving g")
}
on_warning(browser(), f())
on_warning(print(ls()), f())

Thanks,

Hadley


-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-devel mailing list