View Javadoc

1   package com.imcode.db;
2   
3   import java.sql.SQLException;
4   
5   import com.imcode.db.exceptions.IntegrityConstraintViolationException;
6   import com.imcode.db.exceptions.StringTruncationException;
7   import org.apache.commons.lang.StringUtils;
8   
9   public class DatabaseException extends RuntimeException {
10  
11      public DatabaseException( String message, Throwable ex ) {
12          super( message, ex ) ;
13      }
14  
15      public static DatabaseException fromSQLException( SQLException cause ) {
16          return fromSQLException(null, cause) ;
17      }
18  
19      public static DatabaseException fromSQLException( String message, SQLException cause ) {
20          DatabaseException result ;
21          String sqlState = cause.getSQLState();
22          if (null == sqlState) {
23              if (null == message) {
24                  message = cause.getMessage() ;
25              }
26              result = new DatabaseException(message, cause);
27          } else if ( "23000".equals( sqlState ) ) {
28              result = new IntegrityConstraintViolationException( message, cause );
29          } else if ( "01004".equals( sqlState ) ) {
30              result = new StringTruncationException( message, cause );
31          } else {
32              String newMessage = "SQLException with SQLState " + sqlState + ( StringUtils.isBlank(message) ? "" : ": " + message );
33              result = new DatabaseException( newMessage, cause ) ;
34          }
35          return result ;
36      }
37  }