Java SQLException separately according to error code

I need to separate SQLExceptionsaccording to ErrorCode. I have the following statement ifin catch block, but the condition is elsealways printed.

catch (SQLException ex) {

      if (ex.getErrorCode() == 28502){
         System.out.println("Username Problem");
      }

      else{
         System.out.println("Other Problem");
      }  

     Logger.getLogger(FirstTimeMainFrame.class.getName()).log(Level.SEVERE, null, ex);

}

In fact, when I enter unexpected usernamewhen creating a database, the following is called SQLExceptions.

java.sql.SQLException: Failed to create database 'myDB', see the next exception for details.
//rest of exception.
Caused by: ERROR XJ041: Failed to create database 'myDB', see the next exception for details.
//rest of exception.
Caused by: ERROR XBM01: Startup failed due to an exception. See next exception for details
//rest of exception.
Caused by: ERROR 28502: The user name 'AAA.AAA' is not valid.
//rest of exception.

But mine catchalways prints Other Problem. How can I separate different SQLExceptionsaccording to the latter ErrorCode?

+4
source share
2 answers

--- SOLVED ---

Thanks for the redirected comments for @blm.

: Exceptions (1- 2-) String SQLState ErrorCode.

SQLException 3rd exception 28502 SQLState, ErrorCode. 1- 2- Exceptions, .

,

Catch Block;

catch (SQLException se) {

      do {

         if(se.getSQLState().equals("28502")){
            System.out.println("Username Problem");
         }

         else{
            System.out.println("Other Problem");
         }  

      } while ((se = se.getNextException()) != null);

}

:

Other Problem
Other Problem
Username Problem
+1

, getCause() SqlExeption, . Exception .
: Throwable.getCause()

Edit:

SQLException temp = ex;
while(temp.getCause() != null)
{
     temp = (Exception)temp.getCause();
}
//  check if temp is SQLException and if it is check ((SQLException)temp).getErrorCode() == whatever you want
0

Source: https://habr.com/ru/post/1620831/


All Articles