首页 > 解决方案 > 不处理 r 中的 trycatch

问题描述

Try 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))
})

标签: rshinytry-catch

解决方案


将绘图存储为变量并稍后打印有助于 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))
  
})

推荐阅读