'How to stop function when there is a warning?

I am writing a function which requires time. If time is not in the correct format, I would like to stop executing the function. However, it seems when I use tryCatch, although the message shows, the result is still saved and the function finishes.

Here is what I have

date_bad <- "date"
date_good <- "2022-03-25"

    tryCatch(
      date_check <- lubridate::ymd(date),
      warning = function(w) { stop("Hi! date is not in the YYYY-MM-DD format.") }
    )
    # if warning above stop executing, otherwise continue
    print(date_check)



Solution 1:[1]

You could use withCallingHandlers.

f <- function(date) {
  out <- withCallingHandlers(
    date_check <- lubridate::ymd(date),
    warning=function(w) {stop("Hi! date is not in the YYYY-MM-DD format.")}
    )
  return(out)
}

f("2022-03-25")
# [1] "2022-03-25"

f("foo")
# Error in (function (w) : Hi! date is not in the YYYY-MM-DD format.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1