Can you make R print more detailed error messages?

2019-01-31 18:06发布

问题:

I've often been frustrated by R's cryptic error messages. I'm not talking about during an interactive session, I mean when you're running a script. Error messages don't print out line numbers, and it's often hard to trace the offending line, and the reason for the error (even if you can find the location).

Most recently my R script failed with the the incredibly insightful message: "Execution halted." The way I usually trace such errors is by putting a lot of print statements throughout the script -- but this is a pain. I sometimes have to go through the script line by line in an interactive session to find the error.

Does anyone have a better solution for how to make R error output more informative?

EDIT: Many R-debugging things work for interactive sessions. I'm looking for help on command-line scripts run through Rscript. I'm not in the middle of an R session when the error happens, I'm at the bash shell. I can't run "traceback()"

回答1:

Try some of the suggestions in this post:

General suggestions for debugging in R

Specifically, findLineNum() and traceback()/setBreakpoint().



回答2:

@Nathan Well add this line sink(stdout(), type="message") at the beginning of the script and you should get in console message both script content and output along with error message so you can see it as in interactive mode in the console. (you can then also redirect to a log file if you prefer keeping the console "clean")



回答3:

Have a look at my package tryCatchLog (https://github.com/aryoda/tryCatchLog).

While it is impossible to improve the R error messages directly you can save a lot of time by identifying the exact code line of the error and have actual variables at the moment of the error stored in a dump for "post mortem" analysis!

The main advantages of the tryCatchLog function over tryCatch are

  • easy logging of errors, warnings and messages into a file or console
  • warnings do not stop the program execution (tryCatch stops the execution if you pass a warning handler function)
  • identifies the source of errors and warnings by logging a stack trace with a reference to the source file name and line number (since traceback does not contain the full stack trace)
  • allows post-mortem analysis after errors by creating a dump file with all variables of the global environment (workspace) and each function called (via dump.frames) - very helpful for batch jobs that you cannot debug on the server directly to reproduce the error!


回答4:

One way inside a script to get more info on where the error occurred is to redirect R message to the same stream as errors :

sink(stdout(), type="message") 

This way you get both messages and errors in the same output so you see which line raised the error...