[Rd] capturing multiple warnings in tryCatch()

Fox, John j|ox @end|ng |rom mcm@@ter@c@
Fri Dec 3 20:42:34 CET 2021


Dear Adrian,

Here's my slightly modified version of your function, which serves my purpose:

------- snip -------

tryCatchWEM <- function (expr, capture = TRUE) {
    toreturn <- list()
    output <- withVisible(withCallingHandlers(
        tryCatch(expr, 
                 error = function(e) {
                     toreturn$error <<- e$message
                     NULL
                 }), warning = function(w) {
                     toreturn$warning <<- c(toreturn$warning, w$message)
                     invokeRestart("muffleWarning")
                 }, message = function(m) {
                     toreturn$message <<- paste(toreturn$message, m$message, 
                                                sep = "")
                     invokeRestart("muffleMessage")
                 }))
    if (capture & output$visible) {
        if (!is.null(output$value)) {
            toreturn$result <- output$value
        }
    }
    if (length(toreturn) > 0) {
        return(toreturn)
    }
}

------- snip -------

The two small modifications are to change the default of capture to TRUE and to return output$value rather than capture.output(output$value). So a suggestion would be to modify the capture argument to, say, capture=c("no", "output", "value") and then something like

	. . .
	capture <- match.arg(capture)
	. . .
	if (capture == "output"){
      	toreturn$output <- capture.output(output$value)
	} else if (capture == "value"){
		toreturn$value <- output$value
	}
	. . .

Best,
 John

On 2021-12-03, 1:56 PM, "R-devel on behalf of Adrian Dușa" <r-devel-bounces using r-project.org on behalf of dusa.adrian using gmail.com> wrote:

    On Fri, 3 Dec 2021 at 00:37, Fox, John <jfox using mcmaster.ca> wrote:

    > Dear Henrik, Simon, and Adrian,
    >
    > As it turns out Adrian's admisc::tryCatchWEM() *almost* does what I want,
    > which is both to capture all messages and the result of the expression
    > (rather than the visible representation of the result). I was easily able
    > to modify tryCatchWEM() to return the result.
    >

    Glad it helps.
    I would be happy to improve the function, should you send a reprex with the
    desired final result.

    Best wishes,
    Adrian

    	[[alternative HTML version deleted]]

    ______________________________________________
    R-devel using r-project.org mailing list
    https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list