Ujjawal Bhandari
Ujjawal Bhandari

Reputation: 1372

Check tryCatch multiple times

I have script which sends emails to multiple people. Sometimes it returns error so I want to try it 3 more times. If it's not successful in 3 attempts then returns error message. As of now I am using tryCatch() which returns message when error occurs in first attempt and skips to next recipient.

 tryCatch({ CODE HERE }, error=function(e){
                  print("Email not sent")
        })

CODE

library(blastula)

create_smtp_creds_file(
 file = "gmail_secret",
 user = "[email protected]",
 provider = "gmail"
 )

email <- prepare_test_message()

email %>%
  smtp_send(
    from = "[email protected]",
    to = "[email protected]",
    credentials = creds_file(
      "gmail_secret")
  )

Upvotes: 2

Views: 93

Answers (1)

slamballais
slamballais

Reputation: 3235

I would use a while loop:

fails <- 0
success <- FALSE

while (fails < 3 && !success) {
  a <- tryCatch(
    smtp_send(email, 
              from = "[email protected]", 
              to = "[email protected]",
              credentials = creds_file("gmail_secret")
    ), error = function(e) e)
  if (!inherits(a, "simpleError")) {
    success <- TRUE
  } else {
    fails <- fails + 1
  }
}

if (!success) print("Email not sent")

Upvotes: 4

Related Questions