0

I am trying to write a function to handle execution of batch jobs, logging errors and stats of the job results.

Is there a way to reference returning value of expr block, from finally block?

my_do <- function(FUN, ...){

  result <- tryCatch({
      FUN(...)
    }, 
    error = function(e) {
      message("error.")
    },
    finaly = {

      # how can I reference the returning value of FUN(...) in finally block?
      # so for example, I can write code like this:

      message(paste("Result dimensions:", dim(expr_result)))
    },
  )

  return(result)
}
taiyodayo
  • 331
  • 4
  • 13
  • 2
    If `FUN(...)` throws an error, there is no return value from it. I think you might be interested in restarts but your example is neither complete/reproducible nor sufficiently specific. – Roland Jul 30 '20 at 13:22
  • Thank you for the comment Roland, yes as I tried to minimise my original code, I did miss a few bits that makes the questioin a little vague. originally my code had a safety mechanism to return alternative data frame in case of an error. – taiyodayo Jul 31 '20 at 02:18

2 Answers2

1

If the tryCatch return value is being saved into a variable, such as

x <- tryCatch({ 1; }, finally = { message("value is ", x); })
# Error in message("value is ", x) : object 'x' not found

then the answer is no, since the x object does not exist when tryCatch executes finally=.

However, the code block operates within the parent environment, so you can do this instead:

tryCatch({ x <- 1; }, finally = { message("value is ", x); })
# value is 1
x
# [1] 1

This relies on the return value being set without error. If there's an error somewhere in the execution, then ... obviously there will be no value to retrieve.

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    Thank you Evans for making it clear, that without saving the result to an object, I can't reference output from expr block! I falsely assumed there may be a way to reference the return of expr block somehow. I altered my original code as per your suggestion, to make it work as I wished. Hope you have a wonderful day! – taiyodayo Jul 31 '20 at 02:20
1

I suggest that this is not the best way for using finally.

There are following best practices for use finally (http://adv-r.had.co.nz/Exceptions-Debugging.html):

It specifies a block of code (not a function) to run regardless of whether the initial expression succeeds or fails. This can be useful for clean up (e.g., deleting files, closing connections). This is functionally equivalent to using on.exit() but it can wrap smaller chunks of code than an entire function.

codez0mb1e
  • 706
  • 6
  • 17