Solmaz Oskouie
Solmaz Oskouie

Reputation: 66

DataAccessException can not cast to SQLException to get error code and sql state

The below snippet code is from Spring 5 Recipes book (page 386). I'm trying to run and test code but get NullPointerException for sqle variable and further seems there is no relation between SQLException and DataAccessException in Spring 5. Can someone tell me why and how?

package com.apress.springrecipes.vehicle;
...
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;

public class Main {

    public static void main(String[] args) {
        ...
        VehicleDao vehicleDao = context.getBean(VehicleDao.class);
        Vehicle vehicle = new Vehicle("EX0001", "Green", 4, 4);
        try {
            vehicleDao.insert(vehicle);
        } catch (DataAccessException e) {
            SQLException sqle = (SQLException) e.getCause();
            System.out.println("Error code: " + sqle.getErrorCode());
            System.out.println("SQL state: " + sqle.getSQLState());
        }
    }
}

Upvotes: 2

Views: 3247

Answers (1)

Emil Hotkowski
Emil Hotkowski

Reputation: 2343

First of all, you never check if e.getCause() returns null or not. If it returns null your code is vulnerable for NullPointerException

Second point is, why Spring change its way of handling database/jpa exceptions. There are already some conversations about that. For example LINK

Or further you can check out book "Spring in Action" by C. Walls where in chapter about JDBC we can read.

(10.1.1 Getting to know Spring’s data-access exception hierarchy)

On one hand, JDBC’s exception hierarchy is too generic—it’s not much of a hierarchy at all. On the other hand, Hibernate’s exception hierarchy is proprietary to Hibernate. What we need is a hierarchy of data-access exceptions that are descriptive but not directly associated with a specific persistence framework.

I highly recommend whole subchapter to understand this topic.

Upvotes: 1

Related Questions