rovyko
rovyko

Reputation: 4577

How to set R Studio to break on error in code

I used R Studio many months ago and had no problems with the debugger, but now it seems that I can't get the IDE to break and show me the environment where an error has occurred. For example, if I have code split over two files in the working directory, along with a folder named realfolder.

tools.r
savedata <- function (data, path){
  stopifnot(class(data) == "data.frame")
  write.csv(data, path)
}
analysis.r
source("tools.r")

a = c(1,2,3)
b = c(10,20,30)
d = data.frame(a,b)

savedata(d, './realfolder/d.csv') # call A
savedata(1, './realfolder/d.csv') # call B
savedata(d, './fakefolder/d.csv') # call C

When I set Debug -> On Error to Break in Code, and then source analysis.r, an error occurs on the line with call B, and the stop is triggered by stopifnot(class(data) == "data.frame") as expected. However, the IDE does not pause on that line, but only shows the error message:

Error in savedata(1, "./realfolder/d.csv") : 
  class(data) == "data.frame" is not TRUE

Calling traceback() gives all the relevant info, but I remember it was possible to get a snapshot at the time of the error to see what variables in the environment were causing the issue.

When I set Debug -> On Error to Error Inspector I get an interactive traceback, but no break. If I comment out the line with call B, an error will occur in packaged function from call C since fakefolder does not exist. In this case, even the error inspector shows only an error message.

Is this normal behavior? Is it possible to get the effect of browser() at each point in the traceback when an error has occurred?

I'm using RStudio version 1.2.5033

Upvotes: 1

Views: 1054

Answers (2)

Retired Data Munger
Retired Data Munger

Reputation: 1445

put this as the first line of your script:

options(error = utils::recover)

Upvotes: 3

GWD
GWD

Reputation: 1464

Have you tried setting Debug -> On Error to -> Break In Code

enter image description here

I am using RStudio Desktop 1.2.5033

Upvotes: 2

Related Questions