R/ErrorChecking.R

Defines functions ErrorChecking

Documented in ErrorChecking

ErrorChecking <- function(file_conn) {
  sink(type = "message")
  sink(file_conn, type = "output")
  cat(paste("Ended at : ", Sys.time(), "\n\n"))
  sink(type = "output")
  log_file <- showConnections(all=TRUE)[length(showConnections(all=TRUE)[,1])]
  close(file_conn)

  file_conn <- file(description = log_file)
  start <- grep(".*Started.*At.*", readLines(con = file_conn, n = -1L), ignore.case = TRUE)[length(grep(".*Started.*At.*", readLines(con = file_conn, n = -1L), ignore.case = TRUE))] + 1
  end <- grep(".*Ended.*At.*", readLines(con = file_conn, n = -1L), ignore.case = TRUE)[length(grep(".*Ended.*At.*", readLines(con = file_conn, n = -1L), ignore.case = TRUE))] - 1
  if(length(grep(".*error.*", readLines(con = file_conn, n = -1L)[start:end], ignore.case = TRUE)) > 0) {
    email_msg <- paste("Multiple errors thrown. See log file in path :\n\t", log_file, sep = "")
    if(length(grep(".*error.*", readLines(con = file_conn, n = -1L)[start:end], ignore.case = TRUE)) == 1) {
      index_start <- grep(".*Error.*", readLines(con = file_conn, n = -1L)[start:end], ignore.case = TRUE) - 1
      index_end <- index_start
      error_msg <- readLines(con = file_conn, n = -1L)[(start + index_start)]
      while (grepl("^[[:space:]].*|^\\-[[:space:]].*", readLines(con = file_conn, n = -1L)[(start + index_end + 1)], ignore.case = TRUE)) {
        index_end <- index_end + 1
        error_msg <- paste(error_msg, readLines(con = file_conn, n = -1L)[(start + index_end)], sep = "\n")
      }
      email_msg <- paste("Single error thrown at line #",
                         (index_start + start),
                         " in\n\t",
                         log_file,
                         '\n\n',
                         "Error is shown below :\n\n",
                         error_msg,
                         sep = "")
    }
    sendmail(from = "<Domo@usacompression.com>",
             to = "<Domo@usacompression.com>",
             subject = paste("Error Thrown While Running Script", gsub(".*\\/", "", rstudioapi::getSourceEditorContext()$path, ignore.case = TRUE), sep = " "),
             msg = email_msg,
             control = list(smtpServer = "email.usacompression.com"))
  }
  close(file_conn)
  closeAllConnections()
}
cscheller/USACOPMStandard documentation built on Nov. 7, 2019, 12:12 a.m.