0

Try catch block is not handling the error and the error block is not even going inside the error block

Error: Insufficient values in manual scale. 3 needed but only 2 provided.

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))
})
Zatch Lin
  • 9
  • 3
  • The code run perfectly well on my environment result a "No data" plot. – Sinh Nguyen Jun 09 '21 at 06:58
  • You don't need to create plots that show error messages in {shiny}. You can use `validate`/`need` to do that for you. See for example [here](https://stackoverflow.com/questions/29601156/display-error-instead-of-plot-in-shiny-web-app). – TimTeaFan Jun 09 '21 at 08:32
  • 1
    The plot is only build when it is printed. The plot isn't printed inside your `tryCatch` and thus errors during building the plot can't be handled by the `tryCatch`. – Roland Jun 09 '21 at 08:49

1 Answers1

0

Storing the plot as a variable and printing it later helps trycatch to catch the error! Wouldn't work without print.

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))
  
})
Dharman
  • 30,962
  • 25
  • 85
  • 135