1

ご挨拶、

私は mysql の例外に取り組んでいましたが、発生した例外が 2 つの異なる例外名に応答しているという興味深い問題に遭遇しました。どうしてそうなった?

-ダニエル

#!/usr/bin/env ruby

require 'rubygems'
require 'mysql'
require 'yaml'
require 'pp'

$config = YAML.load_file 'database.yml'

class ExceptionPrinter 

  def self.print msg, e
    puts msg
    pp e
  end

end

# sample connect: dbh = Mysql.real_connect $config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['db'], $config['database']['port']

# test 1 - what class is thrown?

begin

  puts "Starting test - MysqlError"
  dbh = Mysql.real_connect $config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['db']
  puts "Error: Code did not throw exception"

rescue MysqlError => e # MysqlError is not a valid exception catch

  ExceptionPrinter.print "MysqlError", e

rescue Exception => e

  ExceptionPrinter.print "Exception class", e

end

# test 2 - What class is thrown?

begin

  puts "Starting test - Mysql::Error"
  dbh = Mysql.real_connect $config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['db']
  puts "Error: Code did not throw exception"

rescue Mysql::Error => e

  ExceptionPrinter.print "Mysql::Error", e

rescue Exception => e

  ExceptionPrinter.print "Exception class", e

end

-- 出力

テストの開始 - MysqlError MysqlError

テストの開始 - Mysql::Error Mysql::Error

4

1 に答える 1

1

一方が他方の単なるエイリアスであるように見えます。

Mysql::Error
# => Mysql::Error
MysqlError
# => Mysql::Error

これに基づいて、MySQLgemのどこかに次のような行があると予想しています。

class Mysql
  MysqlError = Mysql::Error
end

これは、MysqlErrorがクラスMysql::Errorとして定義された定数であることを意味します。

于 2009-11-11T20:46:54.557 に答える