I am writing a Shiny app, but the front-end is actually entirely written in HTML and JavaScript. If any error occurs on the server-side, I would like to simply send its message to the front-end. I was thinking of something along the lines of:
options(shiny.error = function() {
error_message <- geterrmessage()
session$sendCustomMessage(type = 'display-error', message = error_message)
})
The problem with this approach is that session will not be known within the error handling function. Also, even if this were not the case, it overwrites global options.
You always can use getDefaultReactiveDomain to get the session object. Furthermore, you can set the options within your shiny app and reset it via onStop.
Here is a POC.
library(shiny)
js <- HTML("
Shiny.addCustomMessageHandler('catch-error', function(message) {
alert('error caught:' + message.msg)
})
")
ui <- fluidPage(
tags$head(tags$script(js)),
actionButton("err", "Create Error")
)
server <- function(input, output, session) {
op <- options(shiny.error = function() {
session <- getDefaultReactiveDomain()
error_message <- geterrmessage()
session$sendCustomMessage("catch-error", list(msg = error_message))
})
print(getOption("shiny.error"))
onStop(function() options(op))
observeEvent(input$err, {
stop("something bad happened")
})
}
print(getOption("shiny.error"))
shinyApp(ui, server)
print(getOption("shiny.error"))
You can see that a click on Create Error raises an R error, which is however, handled on the JS side (by a simply alert in this case).
Furthermore, after the app closes your options are as they were before the start.
N.B. The app will stop nonetheless, due to stop, but as you can see the error handler is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With