Reputation: 762
When we do an app in shiny we know that:
1 - If you have a function in the server
part and that function returns an error the browser crash/close and the user doesn't know what is going on.
2 - If you have a function that returns an error inside another render function, for example renderDataTable
, the error is shown in the app instead of showing the table.
Knowing the previous 2 points I try to put the functions that are potential to return an error inside the render functions. Doing that the user can see the error.
For example, if I want to show some tables coming from databases and I have a simple query like:
dbGetQuery(con,
statement = glue_sql("SELECT DISTINCT COLUMN1 FROM TABLE1", .con = con)
and COLUMN1
doesn't exist, then the function will rise an error. If I have that function inside the renderDataTable
, then the user can see that something is going wrong with the query. If it is just inside server
then the browser will close.
The problem is that in some situations I can't put the query inside renderDataTable
. What is the approach that we can follow in order to show the error and avoid the crash of the browser?
Thanks
Upvotes: 3
Views: 1889
Reputation: 3986
You could catch the error with trycatch
and display it with showNotification
. I've illustrated this with the Old Faithful Geyser shiny example and added in the trycatch so the app does not crash:
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
server <- function(input, output) {
###
#CATCHING THE ERROR IN A NOTIFICATION
###
tryCatch({
x1 <- DBI::dbGetQuery(con,
statement = glue_sql("SELECT DISTINCT COLUMN1 FROM TABLE1", .con = con))
},
warning = function(warn){
showNotification(paste0(warn), type = 'warning')
},
error = function(err){
showNotification(paste0(err), type = 'err')
})
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
shinyApp(ui = ui, server = server)
Upvotes: 7