Learn R Programming

shinyWidgets (version 0.8.7)

execute_safely: Execute an expression safely in server

Description

Execute an expression without generating an error, instead display the error to the user in an alert.

Usage

execute_safely(
  expr,
  title = "Error",
  message = "An error occured, detail below:",
  include_error = TRUE,
  error_return = NULL,
  session = shiny::getDefaultReactiveDomain()
)

Value

Result of expr if no error, otherwise the value of error_return (NULL by default to use req in other reactive context).

Arguments

expr

Expression to evaluate

title

Title to display in the alert in case of error.

message

Message to display below title.

include_error

Include the error message generated by R.

error_return

Value to return in case of error.

session

Shiny session.

Examples

Run this code
library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  tags$h2("Execute code safely in server"),
  fileInput(
    inputId = "file",
    label = "Try to import something else than a text file (Excel for example)"
  ),
  verbatimTextOutput(outputId = "file_value")
)

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

  options(warn = 2) # turns warnings into errors
  onStop(function() {
    options(warn = 0)
  })

  r <- reactive({
    req(input$file)
    execute_safely(
      read.csv(input$file$datapath)
    )
  })

  output$file_value <- renderPrint({
    head(r())
  })

}

if (interactive())
  shinyApp(ui, server)

Run the code above in your browser using DataLab