Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change reactive value in a tryCatch in shiny

Tags:

r

shiny

Background

In my app I want to allow the user to download a snapshot of an SQL database. As there may be some errors with the SQL connection, I thought of using a tryCatch construct. If there is an error, I want to display a meaningful error message to the user. For that, I created a reactiveVal whose value I set in the error handler bit. I see that the value is changed in the error handler, but the renderPrint function does not fire. Any idea of what I have to change?

Code

library(shiny)

ui <- fluidPage(downloadButton("dat"), verbatimTextOutput("debug"))

server <- function(input, output) {
   errMsg <- reactiveVal()
   output$dat <- downloadHandler(filename = "test.xlsx",
                                 content = function(nF) {
                                    tryCatch({
                                       write.csv(mtcars, nF)
                                       stop("simulate SQL error")
                                    }, error = function(err) {
                                       print("Error Handler")
                                       errMsg("Error")
                                    })

                                 })
   output$debug <- renderPrint(errMsg())

}

shinyApp(ui, server)
like image 893
thothal Avatar asked Nov 18 '25 12:11

thothal


1 Answers

I am not sure why, but tryCatch does not seem to trigger the invalidation of the elements. However you can do it manually. Changing the statement like this seems to work:

tryCatch({
  write.csv(mtcars, nF)
  stop("simulate SQL error")
}, error = function(err) {
  print("Error Handler")
  errMsg("Error")
},
finally = invalidateLater(1))
like image 191
AEF Avatar answered Nov 21 '25 01:11

AEF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!