

package org.midao.jdbc.core.exception;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * Base ExceptionHandler implementation
 */
public class BaseExceptionHandler implements ExceptionHandler {
    private final String dbName;

    /**
     * Creates new BaseExceptionHandler instance.
     *
     * @param dbName Database name
     */
    public BaseExceptionHandler(String dbName) {
        this.dbName = dbName;
    }

    /**
     * {@inheritDoc}
     */
    public MjdbcSQLException convert(Connection conn, SQLException cause, String sql, Object... params) {
        String causeMessage = cause.getMessage();
        if (causeMessage == null) {
            causeMessage = "";
        }
        StringBuffer msg = new StringBuffer(causeMessage);

        msg.append(" Query: ");
        msg.append(sql);
        msg.append(" Parameters: ");

        if (params == null) {
            msg.append("[]");
        } else {
            msg.append(Arrays.deepToString(params));
        }

        MjdbcSQLException ex = new MjdbcSQLException(msg.toString(), cause.getSQLState(),
                cause.getErrorCode());
        ex.setStackTrace(cause.getStackTrace());

        return ex;
    }

}
