-
-
Save paulrougieux/bfeb84d3d116f108d3cda3e497181a57 to your computer and use it in GitHub Desktop.
Catch errors and warnings from log file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load the 2 functions below, | |
# then test errors with: | |
# downloadfile1(url="xxxx", destfile="/tmp/xxxx", logfile="~/rlog.txt") | |
# ~/rlog.txt contains | |
# Error in download.file(url = url, destfile = destfile, ...): cannot download all files | |
# | |
# then | |
# | |
# downloadfile2(url="xxxx", destfile="/tmp/xxxx", logfile="~/rlog.txt") | |
# ~/rlog.txt contains the warning message | |
# simpleWarning in download.file(url = url, destfile = destfile, ...): URL 'HTTP://xxxx/': status was 'Couldn't resolve host name' | |
# but it doesn't contain the error message, how to capture both error and warning? | |
#' Download a file, catch errors only | |
#' @param url an url | |
#' @param destfile, destination file | |
#' @param logfile, log file | |
#' @param ... other parameters passed to \link{download.file} | |
downloadfile1 <- function(url, destfile, logfile, ...){ | |
downloadstatus <- 1 | |
tryCatch({ | |
# Store the download status returned by download.file | |
downloadstatus <- download.file(url = url, destfile = destfile, ...) | |
}, error = function(errorcondition){ | |
# Add error message to the log file | |
write(toString(errorcondition), logfile, append=TRUE) | |
} | |
) | |
# Returns the download status | |
invisible(downloadstatus) | |
} | |
#' Download a file, catch errors and warnings | |
downloadfile2 <- function(url, destfile, logfile, ...){ | |
downloadstatus <- 1 | |
tryCatch({ | |
# Store the download status returned by download.file | |
downloadstatus <- download.file(url = url, destfile = destfile, ...) | |
}, error = function(errorcondition){ | |
# Add error message to the log file | |
write(toString(errorcondition), logfile, append=TRUE) | |
}, warning = function(warningcondition){ | |
# Add warning message to the log file | |
write(toString(warningcondition), logfile, append=TRUE) | |
} | |
) | |
# Returns the download status | |
invisible(downloadstatus) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment