Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate between app crashing and user closing

Tags:

I would like to run code conditionally on whether the user closed the app or the app crashed.

The session$onSessionEnded runs regardless of how the session ended. And I did not find some other function or variable inside session that looked like it could be an indicator on how the session ended.

Basically I would like to use something similar to the commented code in the sample app below. Where crashed would be printed if I click the button, but user ended would be printed if I close the app (eg, close the browser).

library(shiny)
ui <- fluidPage(actionButton('crash', 'crash me'))
server <- function(input, output, session){
  observeEvent(input$crash, stop())
  session$onSessionEnded(function() {
    # if (crashed){
    #   print('crashed')
    # }else{
    #   print('user ended')
    # }
  })
}
shinyApp(ui, server)
like image 304
bobbel Avatar asked Oct 17 '19 12:10

bobbel


1 Answers

You could use shiny.error option to define a custom error handler.

Try:

library(shiny)

ui <- fluidPage(actionButton('crash', 'crash me'))

errorfn <- function() {crashed <<- T }
options(shiny.error = errorfn)
crashed <- F

server <- function(input, output, session){

  session$userData$starttime <- Sys.time()
  observeEvent(input$crash, stop())
  session$onSessionEnded(function() {
    if (crashed) print(paste("Started at :",session$userData$starttime, " - Crashed at : " , Sys.time())) else print("Not crashed, ended by user")
    stopApp(crashed)
    crashed <<- F
  })
}
runApp(list(ui=ui, server=server))

[1] "Started at : 2020-09-15 17:27:41  - Crashed at :  2020-09-15 17:27:45"
[1] TRUE
like image 178
Waldi Avatar answered Oct 02 '22 15:10

Waldi