title: How do I save warnings and errors as output from a function?
body: <p>I'm using <code>lapply</code> to run a complex function on a large number of items, and I'd like to save the output from each item (if any) together with any warnings/errors that were produced so that I can tell which item produced which warning/error. </p>
  
  <p>I found a way to catch warnings using <code>withCallingHandlers</code> (<a href="https://stackoverflow.com/questions/4947528">described here</a>).  However, I need to catch errors as well.  I can do it by wrapping it in a <code>tryCatch</code> (as in the code below), but is there a better way to do it?</p>
  
  <pre><code>catchToList &lt;- function(expr) {
    val &lt;- NULL
    myWarnings &lt;- NULL
    wHandler &lt;- function(w) {
      myWarnings &lt;&lt;- c(myWarnings, w$message)
      invokeRestart("muffleWarning")
    }
    myError &lt;- NULL
    eHandler &lt;- function(e) {
      myError &lt;&lt;- e$message
      NULL
    }
    val &lt;- tryCatch(withCallingHandlers(expr, warning = wHandler), error = eHandler)
    list(value = val, warnings = myWarnings, error=myError)
  } 
  </code></pre>
  
  <p>Sample output of this function is:</p>
  
  <pre><code>&gt; catchToList({warning("warning 1");warning("warning 2");1})
  $value
  [1] 1
  
  $warnings
  [1] "warning 1" "warning 2"
  
  $error
  NULL
  
  &gt; catchToList({warning("my warning");stop("my error")})
  $value
  NULL
  
  $warnings
  [1] "my warning"
  
  $error
  [1] "my error"
  </code></pre>
  
  <p>There are several questions here on SO that discuss <code>tryCatch</code> and error handling, but none that I found that address this particular issue.  See <a href="https://stackoverflow.com/questions/3903157">How can I check whether a function call results in a warning?</a>, <a href="https://stackoverflow.com/questions/4020239">warnings() does not work within a function? How can one work around this?</a>, and <a href="https://stackoverflow.com/questions/2589275">How to tell lapply to ignore an error and process the next thing in the list?</a> for the most relevant ones.</p>