comparison m-toolbox/classes/+utils/@mysql/connect.m @ 40:977eb37f31cb database-connection-manager

User friendlier errors from utils.mysql.connect
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Mon, 05 Dec 2011 18:04:03 +0100
parents 18e956c96a1b
children
comparison
equal deleted inserted replaced
39:11e3ed9d2115 40:977eb37f31cb
3 % 3 %
4 % CALL: 4 % CALL:
5 % 5 %
6 % conn = utils.mysql.connect(hostname, database, username, password) 6 % conn = utils.mysql.connect(hostname, database, username, password)
7 % 7 %
8 % This function returns a Java object implementing the java.sql.Connection 8 % This function returns a Java java.sql.Connection object.
9 % interface connected to the given database using the provided credentials.
10 % If the connection fails because the given username and password pair is not
11 % accepted by the server an utils:mysql:connect:AccessDenied error is thrown.
12 % 9 %
10 % On authetication error an utils:mysql:connect:AccessDenied exception
11 % is thrown. On other errors an utils:mysql:connect:ConnectionError
12 % exception is thrown.
13 13
14 % informative message 14 % informative message
15 import utils.const.* 15 import utils.const.*
16 utils.helper.msg(msg.PROC1, 'connection to mysql://%s/%s username=%s', hostname, database, username); 16 utils.helper.msg(msg.PROC1, 'connection to mysql://%s/%s username=%s', hostname, database, username);
17 17
24 24
25 try 25 try
26 % connect 26 % connect
27 conn = db.connect(uri, pl); 27 conn = db.connect(uri, pl);
28 catch ex 28 catch ex
29 % haven't decided yet if this code should be here or higher in the stack 29 % exceptions handling in matlab sucks
30 if strcmp(ex.identifier, 'MATLAB:Java:GenericException') 30 if strcmp(ex.identifier, 'MATLAB:Java:GenericException')
31 % exceptions handling in matlab sucks 31 % extract exception class and message
32 if ~isempty(strfind(ex.message, 'java.sql.SQLException: Access denied')) 32 lines = regexp(ex.message, '\n', 'split');
33 throw(MException('utils:mysql:connect:AccessDenied', '### access denied').addCause(ex)); 33 p = strfind(lines{2}, ': ');
34 id = lines{2}(1:p(1)-1);
35 message = lines{2}(p(1)+2:end);
36 % some notable cases
37 switch id
38 case 'java.sql.SQLException'
39 throwAsCaller(MException('utils:mysql:connect:AccessDenied', '### access denied: %s', message))
40 case 'com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException'
41 throwAsCaller(MException('utils:mysql:connect:ConnectionError', '### connection error: %s. check database name', message))
42 case 'com.mysql.jdbc.exceptions.jdbc4.CommunicationsException'
43 throwAsCaller(MException('utils:mysql:connect:ConnectionError', '### connection error: %s. check hostname', message))
34 end 44 end
45 % user friendlier exception
46 throwAsCaller(MException('utils:mysql:connect:ConnectionError', '### connection error: %s: %s', id, message))
35 end 47 end
36 rethrow(ex); 48 rethrow(ex);
37 end 49 end
38 end 50 end