Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java SQLException chains: preserve SQLState and linked failures

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

SQLException can carry an SQLState, vendor error code, cause, and linked next exceptions. A diagnostic boundary should retain machine-readable fields without depending on message text.

Operational contract

The method walks at most 47 linked SQLException objects and returns their SQLState and vendor code as immutable entries. It uses getNextException, which is distinct from the normal cause chain. SQLState can be null, so this sample emits UNKNOWN. A service should classify known states under its database policy and preserve the original exception for logging or propagation; collapsing everything to a message string loses useful detail. Do not expose vendor messages directly to clients because they can reveal SQL or data values.

Failure case

A batched write fails and the driver links a primary transaction error to a detailed constraint failure. Recording only the first message loses the later SQLState. This helper retains both codes for an internal decision, while the caller still handles rollback and request response.

Java code

Java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SqlFailureCodes {
    public record Code(String state, int vendorCode) { }

    public static List<Code> inspect(SQLException failure) {
        List<Code> codes = new ArrayList<>();
        for (SQLException current = failure; current != null;
                current = current.getNextException()) {
            if (codes.size() == 47) throw new IllegalStateException("Exception chain exceeds cap");
            String state = current.getSQLState();
            codes.add(new Code(state == null ? "UNKNOWN" : state, current.getErrorCode()));
        }
        return List.copyOf(codes);
    }
}

Performance and ownership cost

Walking E linked exceptions costs O(E) time and O(E) result storage, capped at 47. It does not query the database. A chain cap prevents pathological diagnostic traversal from monopolizing error handling.

Common Mistakes

  • Do not discard next exceptions when diagnosing a batch failure.
  • Do not assume SQLState is always non-null or portable across vendors.
  • Do not send raw database exception messages to external clients.

Connected lessons

java
diagnostics and metadata
jdbc-exception-chain
Storage details