Prevent observer crashes

When an error occurs inside an observer, it leads to a session disconnection. When deploying a Shiny app for production, you wouldn't probably want that, but rather warn the user that a bug occurred, and if possible let him continue using the app.
What are your suggestions for preventing observer crashes (except using trycatch inside each observer)?
Best

Great question. First I want to say this behavior (i.e., an observer error ending the session) was a deliberate design choice. Without that behavior, you have no visual indication when an error happens. That being said, I can understand why you might want to have safe evaluation. Here's a function you could use to try to evaluate an expression within an observer, and if it fails, relay the error in a notification (thanks to @winston for recommending it)

library(shiny)

tryObserve <- function(x) {
  x <- substitute(x)
  env <- parent.frame()
  observe({
    tryCatch(
      eval(x, env),
      error = function(e) {
        showNotification(paste("Error: ", e$message), type = "error")
      }
    )
  })
}

shinyApp(
  fluidPage(
    actionButton("go", "Go")
  ),
  function(input, output) {

    tryObserve({
      if (is.null(input$go) || input$go == 0)
        return()

      message("hi")
      stop("oops")
      message("bye")
    })
        
  }
)
3 Likes

Thank you very much for your reply! It helps me a lot.
Do you have any plan to propose an option for that?

It's not on our current radar, but it's possible that observe() could gain something like an onError = c("disconnect", "notify", "warn") option...If you file an issue on GitHub requesting it we'll be more likely to follow through on it

2 Likes

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.