在R

时间:2018-04-18 21:34:20

标签: r odbc warnings rodbc

我正在构建一个连接到特定密码保护的ODBC数据源的函数,该数据源将用于团队的许多成员 - 它可以在多个环境中使用。如果连接被拒绝,我想显示警告消息,但屏蔽显示的密码。如果我使用suppressWarnings(),就我所知,没有任何东西被捕获,如果我不知道,那么该消息将显示在带有密码的标准输出中。这是迄今为止的功能:

connectToData <- function(uid, pswd, dsn='myDSN') {
  # Function to connect to myDSN data
  #
  # Args:
  #   uid: The user's ID for connecting to the database 
  #   pswd: The user's password for connecting to the database. 
  #   dsn: The DSN for the (already existing) ODBC connection to the 5G  
  #        data. It must be set up on an individual Windows user's machine, 
  #        and they could use any name for it. The default is 'myDSN' 
  #
  # Returns:
  #   The 'RODBC' class object returned by the RODBC:odbcConnect() function.
  #
  # TODO: 1) See if you can specify the connection using odbcDriverConnect()
  #          so as to not rely on user's ODBC connections
  #       2) Capture warnings from odbcConnect() and print them while 
  #          disguising password using gsub, as I've attempted to do below.
  library('RODBC')

  db.conn <- odbcConnect(dsn,
                         uid=uid,
                         pwd=pswd)

  if(class(db.conn) != 'RODBC') {  # Error handling for connections that don't make it
    print(gsub(pswd,'******',warnings()))  # This doesn't work like I want it to
    stop("ODBC connection could not be opened. See warnings()")
  } else {
    return(db.conn)
  }
}

当我使用正确的用户名/密码运行它时,我得到了正确的结果,但是当我使用错误的密码运行它时,我得到了这个:

> db.conn <- connectTo5G(uid='myID',pswd='badpassword', dsn='myDSN') 
[1] "RODBC::odbcDriverConnect(\"DSN=myDSN;UID=myID;PWD=******\")" 
[2] "RODBC::odbcDriverConnect(\"DSN=myDSN;UID=myID;PWD=******\")" 
Error in connectTo5G(uid = "myID", pswd = "badpassword", dsn = "myDSN") :    
ODBC connection could not be opened. See warnings() 
In addition: Warning messages: 
1: In RODBC::odbcDriverConnect("DSN=myDSN;UID=myID;PWD=badpassword") :  
[RODBC] ERROR: state 28000, code 1017, message [Oracle][ODBC][Ora]ORA-01017: invalid username/password; logon denied
2: In RODBC::odbcDriverConnect("DSN=myDSN;UID=myID;PWD=badpassword") :
ODBC connection failed

print(gsub(...))似乎对调用函数之前的最新警告起作用,它也只打印产生警告的函数调用,而不是警告的文本​​。

我想要做的是在“另外:警告消息:”之后捕获所有内容,以便我可以使用gsub(),但在gsub()有机会工作之前避免打印它在上面。我想我需要使用withCallingHandlers(),但我查看了文档和示例,我无法弄明白。

一些额外的背景:这是一个Oracle数据库,在三次尝试连接后锁定用户,所以我想使用stop()以防有人编写多次调用此函数的代码。我小组中的不同用户同时在Windows和Linux中工作(有时会来回移动),因此任何解决方案都需要灵活。

1 个答案:

答案 0 :(得分:2)

捕获错误消息

我不完全理解你想用ODBC完成什么,但是在转换错误信息方面,你可以使用tryCatch作为@joran建议

pswd = 'badpassword'
# Just as a reproducable example, a function which fails and outputs badpassword
failing <- function(){
  badpassword == 1
}
# This would be the error handling part
tryCatch(failing(),
         error = function(e) gsub(pswd, '******', e))
[1] "Error in failing(): object '******' not found\n"
在这种情况下,

e是错误消息,您可以考虑使用其他方法来操纵放置到屏幕上的内容,因此根据替换的内容猜测密码并不容易。例如,注意&#39;对象&#39;如果密码是&#39;对象&#39;那么它也会被替换掉。由于某些原因。甚至是部分单词,也可以被替换。至少,在gsub命令中包含单词边界是有意义的:

pswd = 'ling'
failing <- function(){
  ling == 1
}
tryCatch(failing(),
         error = function(e) gsub(paste0("\\b", pswd, "\\b"), '******', e))
[1] "Error in failing(): object '******' not found\n"

对于其他改进,您应该仔细查看特定的错误消息。

警告

trycatch也可以操纵警告:

pswd = 'ling'
failing <- function(){
  warning("ling")
  ling == 1
}
tryCatch(failing(),
         warning = function(w) gsub(paste0("\\b", pswd, "\\b"), '******', w),
         error = function(e) gsub(paste0("\\b", pswd, "\\b"), '******', e))
[1] "simpleWarning in failing(): ******\n"

然而,这不会显示错误。

withCallingHandlers

如果你真的想要捕获错误和警告的所有输出,你确实需要withCallingHandlers,它的工作方式大致相同,只是它不会终止评估的其余部分。

pswd = 'ling'
failing <- function(pswd){
  warning(pswd)
  warning("asd")
  stop(pswd)
}
withCallingHandlers(failing(),
                    warning = function(w) {
                      w <- gsub(paste0("\\b", pswd, "\\b"), '******', w)
                      warning(w)},
                    error = function(e){
                      e <- gsub(paste0("\\b", pswd, "\\b"), '******', e)
                      stop(e)
                    })