我知道如何捕捉异常,但我们所做的是将“救援”放在代码的可疑部分之后。如果你有很多函数通过 mysql2 gem 向 mysql 发送查询,并且你想捕获它们的异常。您可以做的一件事是在每个文件中添加“救援”声明。但我只想通过一份救援声明来做到这一点。所以我在代码末尾放了一个“救援”,并将所有代码放在“开始”和“结束”中,但它没有用。
这是我的代码,正如您所见,mysql 查询中存在问题,仅仅因为“rescue”是文件的结尾,它没有捕获异常,但是当我将它放在该查询之后它可以工作。
require 'mysql2'
require 'colored'
begin
def log(string)
p "["+string.cyan+"]"
end
def err
p "["+"FAIL".red+"]"
end
def done
p "["+"DONE".red+"]"
end
class SqlClient
def initialize()
log "SqlClient/initialize"
puts "Host: \n"
@host = gets.strip
puts "User: \n"
@user = gets.strip
puts "Pass: \n"
@pass = gets.strip
@client = Mysql2::Client.new(host: @host , username: @user , password: @pass)
end
def list_databases()
puts "We are listing your databases(not just projects) \n \n \n "
@client.query("ELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA").each do |row|
p row["SCHEMA_NAME"]
end
puts "\n \n \n"
end
end
rescue Mysql2::Error
err
abort
end
`query': You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'ELECT SCHEMA_NAME FROM
INFORMATION_SCHEMA.SCHEMATA' at line 1 (Mysql2::Error)
我不是在寻找类似的东西:
begin
# my code
rescue # this line is right after the code which is going to have problem and we catch it.
end
我正在寻找这样的东西:
begin
# first method
# second method
# thrid method
# rest of code and etc ...
# now this is end of file:
rescue
end
但正如您在我的代码中看到的那样,它不起作用。
更新:我在这里发现了一个类似的问题,似乎没有答案:| 也许这是一种红宝石弱点。