From @|mon@urb@nek @end|ng |rom R-project@org  Thu Dec  2 22:14:28 2021
From: @|mon@urb@nek @end|ng |rom R-project@org (Simon Urbanek)
Date: Fri, 3 Dec 2021 10:14:28 +1300
Subject: [Rd] capturing multiple warnings in tryCatch()
In-Reply-To: <E3B708C1-8E1D-41A0-842A-9C05D229B3DB@mcmaster.ca>
References: <E3B708C1-8E1D-41A0-842A-9C05D229B3DB@mcmaster.ca>
Message-ID: <516D77A0-7503-4695-A45F-1162ED816FCF@R-project.org>


Adapted from demo(error.catching):

> W=list()
> withCallingHandlers(foo(), warning=function(w) { W <<- c(W, list(w)); invokeRestart("muffleWarning") })
> str(W)
List of 2
 $ :List of 2
  ..$ message: chr "warning 1"
  ..$ call   : language foo()
  ..- attr(*, "class")= chr [1:3] "simpleWarning" "warning" "condition"
 $ :List of 2
  ..$ message: chr "warning 2"
  ..$ call   : language foo()
  ..- attr(*, "class")= chr [1:3] "simpleWarning" "warning" "condition"

Cheers,
Simon


> On Dec 3, 2021, at 10:02 AM, Fox, John <jfox at mcmaster.ca> wrote:
> 
> Dear R-devel list members,
> 
> Is it possible to capture more than one warning message using tryCatch()? The answer may be in ?conditions, but, if it is, I can't locate it.
> 
> For example, in the following only the first warning message is captured and reported:
> 
>> foo <- function(){
> +   warning("warning 1")
> +   warning("warning 2")
> + }
> 
>> foo()
> Warning messages:
> 1: In foo() : warning 1
> 2: In foo() : warning 2
> 
>> bar <- function(){
> +   tryCatch(foo(), warning=function(w) print(w))
> + }
> 
>> bar()
> <simpleWarning in foo(): warning 1>
> 
> Is there a way to capture "warning 2" as well?
> 
> Any help would be appreciated.
> 
> John
> 
> -- 
> John Fox, Professor Emeritus
> McMaster University
> Hamilton, Ontario, Canada
> Web: http://socserv.mcmaster.ca/jfox/
> 
> 
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 



[Rd] capturing multiple warnings in tryCatch()
Simon Urbanek