Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tryCatch is not catching error and skips error argument

Tags:

I have noticed below error is not catched properly by tryCatch: it doesnt print TRUE, and it doesnt go to the browser...

Could it be a bug in the tryCatch function?

library(formattable)
df1 = structure(list(date = c("2018-12-19", "2018-12-19"), 
                     imo = c(9453391, 9771298), 
                     name = c("SFAKIA WAVE", "MEDI KYOTO"), 
                     speed = c(10.3000001907349, 11.6999998092651), 
                     destination = c("ZA DUR", "ZA RCB"), 
                     subsize = c("Post Panamax", "Post Panamax"), 
                     eta = c("2018-12-27 09:00:00", "2018-12-27 09:00:00"), 
                     ToSAF = c(TRUE, TRUE)), 
                .Names = c("date", "imo", "name", "speed", "destination", "subsize", "eta", "ToSAF"), 
                row.names = c(NA, -2L), 
                class = "data.frame")

tryCatch(expr = {
  L = list(formattable::area(row = 3)  ~ formattable::formatter('span', style = x ~ formattable::style(display = 'block', 'border-radius' = '4px', 'padding-right' = '4px')))
  formattable::formattable(df1, L)
  }, 
  error = function(e) {
    print(TRUE)
    browser()
  } 
)
like image 469
RockScience Avatar asked Dec 20 '18 10:12

RockScience


People also ask

How to catch error message in R?

In R Programming, there are basically two ways in which we can implement an error handling mechanism. Either we can directly call the functions like stop() or warning(), or we can use the error options such as “warn” or “warning. expression”.

How do I skip an error in R?

The simplest way of handling conditions in R is to simply ignore them: Ignore errors with try() . Ignore warnings with suppressWarnings() . Ignore messages with suppressMessages() .


1 Answers

There is no error when evaluating expression formattable::formattable(df1, L). You can verify by running:

L <- list(formattable::area(row = 3)  ~ formattable::formatter('span', style = x ~ formattable::style(display = 'block', 'border-radius' = '4px', 'padding-right' = '4px')))
test <- try(formattable::formattable(df1, L))
class(test)
[1] "formattable" "data.frame" 

In case of error the class should be "try-error". The error appears when you try to print the output of your expression to the console. I think you want:

L <- list(formattable::area(row = 3)  ~ formattable::formatter('span', style = x ~ formattable::style(display = 'block', 'border-radius' = '4px', 'padding-right' = '4px')))
test <- formattable::formattable(df1, L)
tryCatch(expr = {
  print(test)
  }, 
  error = function(e) {
    print(TRUE)
    browser()
  } 
)
like image 136
pieca Avatar answered Sep 27 '22 20:09

pieca