R: Catch errors and continue execution after logging the stacktrace (no traceback available with tryCatch)
<p>I have many unattended batch jobs in R running on a server and I have to analyse job failures after they have run.</p>

<p>I am trying to catch errors to log them and recover from the error gracefully but I am not able to get a stack trace (<code>traceback</code>) to log the code file name and line number of the R command that caused the error. A (stupid) reproducible example:</p>

<pre><code>f &lt;- function() {
  1 + variable.not.found    # stupid error
}

tryCatch( f(), error=function(e) {
  # Here I would log the error message and stack trace (traceback)
  print(e)            # error message is no problem
  traceback()         # stack trace does NOT work
  # Here I would handle the error and recover...
})
</code></pre>

<p>Running the code above produces this output:</p>

<blockquote>
  <p>simpleError in f(): object 'variable.not.found' not found</p>
  
  <p><strong>No traceback available</strong></p>
</blockquote>

<p>The traceback is not available and the reason is documented in the R help  (<code>?traceback</code>):</p>

<blockquote>
  <p>Errors which are caught via try or tryCatch do not generate a
  traceback, so what is printed is the call sequence for the last
  uncaught error, and not necessarily for the last error.</p>
</blockquote>

<p>In other words: Catching an error with <code>tryCatch</code> does kill the stack trace!</p>

<p>How can I</p>

<ul>
<li>handle errors <strong>and</strong></li>
<li>log the stack trace (traceback) for further examination</li>
<li>[optionally] without using undocumented or hidden R internal functions that are not guaranteed to work in the future?</li>
</ul>

<p>THX a lot!</p>