Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add tryn()? #80

Closed
jmbarbone opened this issue Jan 15, 2022 · 0 comments · Fixed by #217
Closed

add tryn()? #80

jmbarbone opened this issue Jan 15, 2022 · 0 comments · Fixed by #217
Labels
easier 🐇 Minimal work help wanted 🏳️ Extra attention is needed new feature 🎁 New feature request
Milestone

Comments

@jmbarbone
Copy link
Owner

I like the name

tryn <- function(expr, n = 10, silent = TRUE) {
  e <- parent.frame()
  attempt <- 0
  expr <- as.expression(substitute(expr))
  while (inherits(res <- try(eval(expr, envir = e), silent = silent), "try-error")) {
    attempt <- attempt + 1
    if (attempt == n) {
      cond <- attr(res, "condition")
      msg <- paste0(
        "tryn() failed: maximum attempts reached: ", attempt, "\n",
        "Error in ", as.character(as.expression(cond[["call"]])), " : ",
        cond[["message"]]
      )
      stop(simpleError(msg))
    }
  }
  
  res
}

foo <- function() stop("I added an error")
tryn(n = 10, foo())
#> Error: tryn() failed: maximum attempts reached: 10
#> Error in foo() : I added an error

Created on 2022-01-15 by the reprex package (v2.0.1)

@jmbarbone jmbarbone added the enhancement 💎 Feature enhancement label Jan 15, 2022
@jmbarbone jmbarbone added this to the 0.4.3 milestone Jan 15, 2022
@jmbarbone jmbarbone added easier 🐇 Minimal work new feature 🎁 New feature request and removed enhancement 💎 Feature enhancement labels Jan 15, 2022
@jmbarbone jmbarbone added the help wanted 🏳️ Extra attention is needed label Apr 19, 2022
@jmbarbone jmbarbone modified the milestones: 0.5.2, future Oct 11, 2022
jmbarbone added a commit that referenced this issue Oct 25, 2023
jmbarbone added a commit that referenced this issue Oct 25, 2023
jmbarbone added a commit that referenced this issue Oct 25, 2023
@jmbarbone jmbarbone mentioned this issue Oct 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
easier 🐇 Minimal work help wanted 🏳️ Extra attention is needed new feature 🎁 New feature request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant