Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R trycatch() in place with err and warn handlers but Shiny still crashes?

Tags:

r

try-catch

shiny

To reproduce:

#app.R
library(shiny)
library(RODBC)
savefunc <- function() {
      conn <- odbcConnect(...) #put in a conn string u know works
      df = data.frame(testing=c("testing"))
      columnTypes = list(testing="varchar(128)")
      tryCatch(
        {
          sqlSave(conn, dat=df, tablename ="...", #put in a pre-existing tbl
            rownames = FALSE, colnames = FALSE, append=TRUE, varTypes=columnTypes)
        },
        err=function(errorCondition) {
          cat("in err handler")
          message(errorCondition)
        },
        warn=function(warningCondition) {
           cat("in warn handler")
          message(warningCondition)
        },
        finally={
          odbcClose(conn)
        }
      )
    }

server <- function(input, output) {
  observeEvent(input$doBtn, {
    savefunc()
  })
}

ui <- shinyUI(fluidPage(
  mainPanel(
    actionButton("doBtn", "Do something")
  )
))

shinyApp(ui = ui, server = server)

Errors aren't caught... while R still seems to run (hasn't crashed), when you look at the Shiny app / UI you will see that it's died. The error in the console is something like:

Warning: Unhandled error in observer: unable to append to table xxx
observeEvent(input$doBtn)

(You may get sthing slightly diff based on the example above) but the point is that the error will now have travelled up to the observer in shiny. Is there a way to get the shiny app itself to also fail over? Or suppress the error inside the observer?

like image 632
rstruck Avatar asked Oct 23 '25 15:10

rstruck


1 Answers

I just had a very similar experience (uncatched errors), and as a matter of fact, just had to replace err=function(e) with error=function(e) (and I guess it goes the same for warn and warning).


EDIT :

I actually just tried with your code, and for me it works when I do this :

savefunc <- function() {
    tryCatch({
        conn <- odbcConnect(...)
        df = data.frame(testing=c("testing"))
        columnTypes = list(testing="varchar(128)")
        tryCatch({
            sqlSave(conn, dat=df, tablename="...", rownames=FALSE, colnames=FALSE, append=TRUE, varTypes=columnTypes)
        }, error=function(e) {
            cat(paste("in err handler\n"),e)
        }, warning=function(w) {
            cat(paste("in warn handler\n"),w)
        }, finally={
            odbcClose(conn)
        })
    }, error=function(e) {
        cat(paste("in err handler2\n"),e)
    }, warning=function(w) {
        cat(paste("in warn handler2\n"),w)
    })
}

It is obviously very dirty, and I am not really sure why it works. I just got rid of the message() calls and encapsulated two trycatch(). Deserves a try, maybe.

like image 136
Vongo Avatar answered Oct 25 '25 04:10

Vongo