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

R语言如何用tryCatch()将错误和警告存储到列表中

问题原因

tryCatch的error、warning处理函数是独立的局部作用域,你在函数内部定义的hosp_e、hosp_w仅在函数运行时有效,运行结束就会被销毁,finally块访问不到这两个局部变量,所以exists("hosp_e")永远返回FALSE,最终列表里只能拿到默认的"No Error"。

修改方案
  • 在tryCatch外层预先初始化错误、警告变量,默认值设为无异常的状态,保证所有分支都能访问并修改这两个变量
  • 在error、warning处理分支中,用超赋值运算符<<-修改外层的预定义变量,避免变量仅存在于局部作用域
  • 将结果列表hospitals_output也定义在tryCatch外层,避免tryCatch运行结束后结果被销毁
修正后的完整代码
# 加载依赖包
library(jsonlite)

# 预先初始化变量,作用域为当前环境,所有分支都可访问修改
hosp_error <- "No Error"
hosp_warning <- "No Warning"
hospitals_output <- list()
hospitals_url <- "https://services1.arcgis.com/Hp6G80Pky0om7QvQ/arcgis/rest/services/Hospitals_1/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json"
hospitals_df <- data.frame()

tryCatch({
  hospitals_num <- c(0, 2000, 4000, 6000)
  hosget <- lapply(hospitals_num, function(num) {
    hospitals_url_loop <- paste0(hospitals_url, "&resultOffset=", num)
    hospitals_json <- fromJSON(hospitals_url_loop)
    as.data.frame(hospitals_json$features$attributes)
  })
  hospitals_df <- do.call(rbind, hosget)
},
error = function(e){
  # 用<<-修改外层预定义的错误变量
  hosp_error <<- "Error: Hospital data has not been collected due to an error. Please ensure that the number loop is correct."
  print(hosp_error)
},
warning = function(w){
  # 用<<-修改外层预定义的警告变量
  hosp_warning <<- "Warning: Hospital data has not been collected. Please ensure that the number loop is correct."
  print(hosp_warning)
},
finally = {
  hospitals_log <- paste("Hospitals Code Has Been Executed on ", Sys.Date())
  print(paste(hospitals_log, ", ", hosp_error, ", ", hosp_warning))
  # 组装结果列表,同时存入拉取到的数据(拉取失败时为空数据框)
  hospitals_output <<- list(
    log = hospitals_log,
    error = hosp_error,
    warning = hosp_warning,
    url = paste("URL: ", hospitals_url),
    data = hospitals_df
  )
  # 清理中间变量
  rm(hospitals_num, hosget, hospitals_log)
})

# 运行结束后直接访问hospitals_output即可拿到所有结果
验证说明

你可以主动修改url构造错误场景,运行结束后打印hospitals_output$error就能看到自定义的错误信息,正常拉取成功时error和warning字段会显示默认的无异常状态,拉取到的数据存在hospitals_output$data里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:09:02