@@ -100,12 +100,21 @@ public final void clear() {
100100 addRCode (RCodeIO .getInterprocessDependencies (rCallerOptions ));
101101 }
102102
103+ /**
104+ * Adding R code that exports toplevel var to outputFile for reading by Java. Internal use only.
105+ * @param outputFile file to be created
106+ * @param var name of variable to be exported
107+ */
103108 public void appendStandardCodeToAppend (File outputFile , String var ) {
104109 addRCode (RCodeIO .getVariableExporting (rCallerOptions , var , URI .create (outputFile .getAbsolutePath ())));
105110 }
106111
112+ static String createEndSignalCode (File outputFile ) {
113+ return ("cat(1, file=\" " + outputFile .getPath ().replace ("\\ " , "/" ) + "\" )\n " );
114+ }
115+
107116 public void appendEndSignalCode (File outputFile ) {
108- addRCode ("cat(1, file= \" " + outputFile . getPath (). replace ( " \\ " , "/" ) + " \" ) \n " );
117+ addRCode (createEndSignalCode ( outputFile ) );
109118 }
110119
111120 public void clearOnline (){
@@ -245,7 +254,7 @@ public void R_source(String sourceFile) {
245254 }
246255
247256 public void deleteTempFiles (){
248- if (tempFileService != null ){
257+ if (tempFileService != null ){
249258 tempFileService .deleteRCallerTempFiles ();
250259 }
251260 }
@@ -254,4 +263,29 @@ public void deleteTempFiles(){
254263 public String toString () {
255264 return this .code .toString ();
256265 }
266+
267+ /**
268+ * Wrap current code to standard tryCatch function.
269+ * Error handler saves details to errorOutputFile if the error occurs.
270+ * @param errorOutputFile
271+ * @return
272+ */
273+ String toTryCatchScript (File errorOutputFile ) {
274+ //Using code snippet "An improved “error handler”" with withCallingHandlers nested in tryCatch
275+ //from https://cran.r-project.org/web/packages/tryCatchLog/vignettes/tryCatchLog-intro.html
276+
277+ var script = new StringBuilder ("tryCatch( withCallingHandlers({\n " );
278+ script .append (this .code );
279+
280+ script .append ("}, error=function(e) {\n " +
281+ " stacktrace <- as.character(sys.calls())\n " +
282+ " exception <- as.character(e)\n " +
283+ " caught <- list()\n " +
284+ " caught[[1]] <- exception\n " +
285+ " caught[[2]] <- stacktrace[6:(length(stacktrace)-2)]\n " + //remove wrapping steps
286+ " names(caught) <- c(\" exception\" , \" stacktrace\" )\n " );
287+ script .append (RCodeIO .getVariableExporting (rCallerOptions , "caught" , URI .create (errorOutputFile .getAbsolutePath ()))).append ("\n " );
288+ script .append ("}), error = function(e) { })\n " );
289+ return script .toString ();
290+ }
257291}
0 commit comments