Creating a suppressConditions function to suppress everything

Viewed 41

I have been meaning to write a suppressConditions function to suppress every condition such as error, warning and message. For that purpose I have reviewed the source code of suppressMessage and suppressWarning functions and couldn't figure out why the classes argument only contains one condition and we cannot use a general function for both purposes:

I would like to know why this code works in muffling either message or warning condition, whereas the following code doesn't:

suppressConditions <- function(expr, condition = "message") {
  withCallingHandlers(
    condition = function(cons) {
      if(inherits(cons, condition)) {
        rlang::cnd_muffle(cons)
      }
    },
    expr
  )
}

suppressConditions(message("hello!")) # It works

suppressConditions <- function(expr, conditions = c("message", "warning")) {
  withCallingHandlers(
    conditions = function(cons) {
      if(inherits(cons, conditions)) {
        rlang::cnd_muffle(cons)
      }
    },
    expr
  )
}

> suppressConditions(message("hello!")) # It doesn't work
hello!

So in the end I would like to know how I can add error condition to this function so that it suppress all three conditions.

Thank you very much in advance.

1 Answers

So you need to pass the different condition handlers as separate params to withCallingHandlers. The easiest way to do that is to build a list of parameters and then use do.call to actually call the function.

This should work

suppressConditions <- function(expr, conditions = c("message", "warning")) {
  fn <- function(cons) {
    if(inherits(cons, conditions)) {
      rlang::cnd_muffle(cons)
    }
  }
  conds <- setNames(rep(list(fn), length(conditions)), conditions)
  invisible(do.call("withCallingHandlers", c(list(substitute(expr)), conds)))
}

suppressConditions(message("hello!"))
suppressConditions(warning("oops!"))

We make a list that repeats the handling functions for each condition type and then name that the condition name. We combine that with expr in a list, wrapping it in substitute() so we don't evaluate it prematurely. This will call the function with the correct parameters.

Related