Skip to content

Commit 4e6369b

Browse files
committed
Implement more specific exception classes
1 parent c21af01 commit 4e6369b

2 files changed

Lines changed: 15 additions & 7 deletions

File tree

lib/mysql2/error.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ class Error < StandardError
88
replace: '?'.freeze,
99
}.freeze
1010

11+
BaseConnectionError = Class.new(Error)
12+
13+
CODES = {
14+
1045 => AccessDenied = Class.new(BaseConnectionError),
15+
2005 => UnknownHost = Class.new(BaseConnectionError),
16+
}
17+
1118
attr_reader :error_number, :sql_state
1219

1320
# Mysql gem compatibility
@@ -23,7 +30,8 @@ def initialize(msg, server_version = nil, error_number = nil, sql_state = nil)
2330
end
2431

2532
def self.new_with_args(msg, server_version, error_number, sql_state)
26-
new(msg, server_version, error_number, sql_state)
33+
error_class = CODES.fetch(error_number, self)
34+
error_class.new(msg, server_version, error_number, sql_state)
2735
end
2836

2937
private

spec/mysql2/client_spec.rb

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@
1919
end
2020
end
2121

22-
it "should raise an exception upon connection failure" do
22+
it "should raise a Mysql::Error::UnknownHost upon connection failure" do
2323
expect do
2424
# The odd local host IP address forces the mysql client library to
2525
# use a TCP socket rather than a domain socket.
2626
new_client('host' => '127.0.0.2', 'port' => 999999)
27-
end.to raise_error(Mysql2::Error)
27+
end.to raise_error(Mysql2::Error::UnknownHost)
2828
end
2929

3030
it "should raise an exception on create for invalid encodings" do
@@ -924,10 +924,10 @@ def run_gc
924924
end
925925
end
926926

927-
it "should raise a Mysql2::Error exception upon connection failure" do
928-
expect do
929-
new_client(host: "localhost", username: 'asdfasdf8d2h', password: 'asdfasdfw42')
930-
end.to raise_error(Mysql2::Error)
927+
it "should raise a Mysql2::Error::AccessDenied exception upon connection failure due to invalid credentials" do
928+
expect {
929+
new_client(:host => "localhost", :username => 'asdfasdf8d2h', :password => 'asdfasdfw42')
930+
}.to raise_error(Mysql2::Error::AccessDenied)
931931

932932
expect do
933933
new_client(DatabaseCredentials['root'])

0 commit comments

Comments
 (0)