diff 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
line wrap: on
line diff
--- a/m-toolbox/classes/+utils/@mysql/connect.m	Mon Dec 05 16:20:06 2011 +0100
+++ b/m-toolbox/classes/+utils/@mysql/connect.m	Mon Dec 05 18:04:03 2011 +0100
@@ -5,11 +5,11 @@
 %
 %   conn = utils.mysql.connect(hostname, database, username, password)
 %
-% This function returns a Java object implementing the java.sql.Connection
-% interface connected to the given database using the provided credentials.
-% If the connection fails because the given username and password pair is not
-% accepted by the server an utils:mysql:connect:AccessDenied error is thrown.
+% This function returns a Java java.sql.Connection object.
 %
+% On authetication error an utils:mysql:connect:AccessDenied exception
+% is thrown. On other errors an utils:mysql:connect:ConnectionError
+% exception is thrown.
 
   % informative message
   import utils.const.*
@@ -26,12 +26,24 @@
     % connect
     conn = db.connect(uri, pl);
   catch ex
-    % haven't decided yet if this code should be here or higher in the stack
+    % exceptions handling in matlab sucks
     if strcmp(ex.identifier, 'MATLAB:Java:GenericException')
-      % exceptions handling in matlab sucks
-      if ~isempty(strfind(ex.message, 'java.sql.SQLException: Access denied'))
-        throw(MException('utils:mysql:connect:AccessDenied', '### access denied').addCause(ex));
+      % extract exception class and message
+      lines = regexp(ex.message, '\n', 'split');
+      p = strfind(lines{2}, ': ');
+      id = lines{2}(1:p(1)-1);
+      message = lines{2}(p(1)+2:end);
+      % some notable cases
+      switch id
+        case 'java.sql.SQLException'
+          throwAsCaller(MException('utils:mysql:connect:AccessDenied', '### access denied: %s', message))
+        case 'com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException'
+          throwAsCaller(MException('utils:mysql:connect:ConnectionError', '### connection error: %s. check database name', message))
+        case 'com.mysql.jdbc.exceptions.jdbc4.CommunicationsException'
+          throwAsCaller(MException('utils:mysql:connect:ConnectionError', '### connection error: %s. check hostname', message))
       end
+      % user friendlier exception
+      throwAsCaller(MException('utils:mysql:connect:ConnectionError', '### connection error: %s: %s', id, message))
     end
     rethrow(ex);
   end