print JDBC Exception Msg - Java java.sql

Java examples for java.sql:SQLException

Description

print JDBC Exception Msg

Demo Code


import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    /**//from w  ww.  j a v  a 2 s .co m
     * @param ex <p>
     * @return
     */
    public static String printJDBCExceptionMsg(SQLException ex) {
        String stackTracedAsString = "";
        String err = "";
        for (Throwable e : ex) {
            stackTracedAsString += StringUtils
                    .throwableStackTraceToString(ex);
            if (e instanceof SQLException) {
                String state = ((SQLException) e).getSQLState();
                if (state != null && !state.isEmpty()) {
                    stackTracedAsString += "\nState: " + state
                            + "\nMessage: " + e.getMessage();
                }
                e.printStackTrace(System.err);
                err += "\nSQLState: " + ((SQLException) e).getSQLState();
                err += "\nError Code: " + ((SQLException) e).getErrorCode();
                err += "\nMessage: " + e.getMessage();
                Throwable t = ex.getCause();
                while (t != null) {
                    err += "\nCause: " + t;
                    t = t.getCause();
                }
                if (state != null) {
                    if (((SQLException) e).getSQLState().equalsIgnoreCase(
                            "S1000")) {
                        err += "\nDetails: Cannot insert a record with that ID already exists.";
                    } else if (((SQLException) e).getMessage()
                            .toLowerCase().contains("foreign key")) {
                        err += "\nDetails: Invalid foreign key reference.";
                    } else if (((SQLException) e).getMessage()
                            .toLowerCase().contains("duplicate entry")) {
                        err += "\nDetails: Duplicate entry (PK).";
                    } else if (((SQLException) e).getMessage()
                            .toLowerCase().contains("incorrect syntax")) {
                        err += "\nDetails: Syntax Error.";
                    }
                }

            }
        }
        return StringUtils.coalesce(err, stackTracedAsString,
                ex.toString(), "UNKNOWN");
    }
}

Related Tutorials