Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Catch errors and warnings from log file
# 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
You can’t perform that action at this time.