Sometimes I run into an issue where the database query generates error. One example is:
nanodbc/nanodbc.cpp:3069: 07009: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index
I know why the error occurs but I can't seem to catch the error to try something else when something like this happens.
result <- tryCatch(
      data <- tbl(conn, query),
      
      error = function(e){
        
        print("Error encountered: ", e)
        print("Attempting to run by sorting the columns")
        
        
        new_query <- create_query_with_column_names(query)
        
        print("Attempting to fetch the data with the new query")
        data <- tbl(conn, new_query)
        
        end_time <- Sys.time()
        
        
        show_query_runtime(total_time=end_time-start_time, caller="fetch data without lazy loading.")
        
      }
    )
But instead, the code runs without error, but when I run the result, I get the error again.
> result
Error in result_fetch(res@ptr, n) : 
  nanodbc/nanodbc.cpp:3069: 07009: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index 
Warning message:
In dbClearResult(res) : Result already cleared
The above code won't catch the error. Why? How can I fix this?
 
    