【问题标题】:not handling trycatch in r不处理 r 中的 trycatch
【发布时间】:2021-06-09 06:54:35
【问题描述】:

尝试 catch 块没有处理错误并且错误块甚至没有进入错误块

错误:手动刻度中的值不足。需要 3 个,但只有 2 个 提供。

c("#B71D48","#ECE189") -> colors_set

tryCatch({

iris %>% 
  ggplot(aes(x=Petal.Length, y=Petal.Width, color=Species))+
    geom_point()+
    scale_color_manual(values = colors_set)  
  
},error = function(e){
  #error handling code
  print("inside error")
  ggplot() +
    theme_void() +
    geom_text(aes(0,0) ,
              label = "No data",
              size=20)+
    theme(plot.background = element_rect(fill = "white",color = "#ffbf00", size=7))
})

【问题讨论】:

  • 代码在我的环境中运行得非常好导致“无数据”图。
  • 您不需要创建在 {shiny} 中显示错误消息的图。您可以使用validate/need 为您执行此操作。参见例如here
  • 绘图仅在打印时构建。该图未打印在您的tryCatch 中,因此tryCatch 无法处理构建图期间的错误。

标签: r shiny try-catch


【解决方案1】:

将绘图存储为变量并稍后打印有助于 trycatch 捕获错误!没有打印就无法工作。

library(tidyverse)

c("#B71D48","#ECE189") -> colors_set

iris %>% 
  ggplot(aes(x=Petal.Length, y=Petal.Width, color=Species))+
  geom_point() +
  scale_color_manual(values = colors_set) -> x

tryCatch(print(x), error = function(e) {
  
  #error handling code
  print("inside error")
  ggplot() +
    theme_void() +
    geom_text(aes(0,0) ,
              label = "No data",
              size=20)+
    theme(plot.background = element_rect(fill = "white",color = "#ffbf00", size=7))
  
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多