You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R Shiny中用tryCatch/showNotification捕获全局函数内stop()错误

R Shiny 错误捕获实现方案

全局定义CheckOdd函数

先在全局环境定义包含stop()的目标函数:

# 全局定义的检查奇数函数
CheckOdd <- function(num) {
  if (!is.numeric(num)) {
    stop("输入必须是数值类型")
  }
  if (num %% 2 == 0) {
    stop("输入数值是偶数,不符合要求")
  }
  # 生成结果表格
  data.frame(输入数值 = num, 检查结果 = "奇数,符合要求", 检查时间 = Sys.time())
}

Shiny 应用代码

UI 部分

ui <- fluidPage(
  numericInput("mynum", "输入一个数值", value = NULL),
  actionButton("assessBtn", "Assess"),
  tableOutput("resultTable"),
  tableOutput("historyTable")
)

Server 部分

核心用tryCatch包裹函数调用,出错时通过showNotification展示错误,保证应用不崩溃:

server <- function(input, output, session) {
  # 初始化存储输入的列表和历史数据表
  inputList <- reactiveVal(list())
  resultHistory <- reactiveVal(data.frame(输入数值 = numeric(), 检查结果 = character(), 检查时间 = POSIXct(), stringsAsFactors = FALSE))
  
  observeEvent(input$assessBtn, {
    # 获取输入值
    input_num <- input$mynum
    
    # 将输入存入列表
    current_list <- inputList()
    current_list[[length(current_list) + 1]] <- input_num
    inputList(current_list)
    
    # 用tryCatch捕获错误
    tryCatch({
      # 调用全局CheckOdd函数生成结果表
      res_table <- CheckOdd(input_num)
      # 更新结果表输出
      output$resultTable <- renderTable(res_table)
      
      # 将结果存入历史数据表
      current_history <- resultHistory()
      resultHistory(rbind(current_history, res_table))
    }, error = function(e) {
      # 清空当前结果表输出
      output$resultTable <- renderTable(NULL)
      # 弹出错误通知
      showNotification(
        paste("错误信息:", e$message),
        type = "error",
        duration = 5,
        closeButton = TRUE
      )
    })
  })
  
  # 渲染历史数据表
  output$historyTable <- renderTable(resultHistory())
}

shinyApp(ui, server)

关键说明

  • tryCatch块包裹了CheckOdd的调用及后续结果处理逻辑,函数触发stop()时会自动进入error分支执行错误处理
  • showNotification直接在页面弹出错误提示,无需使用verbatimText组件
  • CheckOdd保持全局环境定义,未放入server内部
  • 错误发生时会清空当前结果表,仅当函数执行成功时才会添加历史记录(可根据需求调整该逻辑)

内容的提问来源于stack exchange,提问作者aiorr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:04:51