Make safeError behave in observeEvent as it does within eventReactive

I'd been using eventReactive in an app, but then switched some uses of eventReactive to observeEvent and the error handling changed. That is, an error handled by safeError within eventReactive would not kill the app but instead display the error message in the UI - but the same code handled within observeEvent makes the app crash. I'm probably missing something obvious. What is that thing?

Here's a minimal shiny app to demonstrate the issue:

library(shiny)
library(bslib)
library(ggplot2)

ui <- page_sidebar(
  title = h1(
    class = "bslib-page-title",
    "Errors when bins == 29"
  ),

  sidebar = sidebar(
    title = "Histogram controls",
    numericInput("bins", "Number of bins", 30),
    actionButton("submit_button", "Submit"),
    actionButton("send_button", "Send")
  ),

  card(
    card_header("Histogram"),
    plotOutput("p")
  )
)

server <- function(input, output) {
  make_plot <- function() {
    ggplot(iris) +
      geom_histogram(aes(Sepal.Length), bins = input$bins) +
      theme_bw(base_size = 20)
  }
  observeEvent(input$submit_button, {
    if (input$bins == 29) stop(safeError("Error in stuff"))
    output$p <- renderPlot({ make_plot() })
  })
  xx <- eventReactive(input$send_button, {
    if (input$bins == 29) stop(safeError("Error in things"))
    make_plot()
  })
  output$p <- renderPlot({ xx() })
}

shinyApp(ui, server)

Ah nevermind, I think I just needed to put the error handling within the render fxn, so

observeEvent(input$submit_button, {
    output$p <- renderPlot({ 
        if (input$bins == 29) stop(safeError("Error in stuff"))
        make_plot() 
    })
})

instead of

observeEvent(input$submit_button, {
    if (input$bins == 29) stop(safeError("Error in stuff"))
    output$p <- renderPlot({ make_plot() })
})

This topic was automatically closed 7 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.