EliteRaceElephant EliteRaceElephant - 9 days ago 6
MySQL Question

Handle via Exceptions: com.mysql.jdbc.MysqlDataTruncation

My Java is somewhat rusty and I want to increase the quality of my code. I want to handle expectable errors with exceptions but do not really know how.

I am aware of try catch. But mine always looks like this without any handling:

try { ...}

catch (SQLException e) {
e.printStackTrace();
System.exit(1);
}


I am using Java JDBC with MySQL and I get this concrete error:

com.mysql.jdbc.MysqlDataTruncation: Data truncation:
Data too long for column 'column_name'


It is clear that the value was too large and needs to be truncated. Surely I can check the input before giving it to the database but there might be other errors I also want to handle.

How do I remedy this via exception handling? Is SQLException the right Exception for my error?

There is this duplicate question: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'column_name'. However it does not discuss how to handle it via exceptions.

Answer

How do I remedy this via exception handling ?

Yes, as you already mentioned, your application should cover all of the input validations properly before it is entering into the DAO layer so that the request will not hit/reach the database and fail. For this, you can make use of javax validations (like Min, Max size, etc.., look here) on the DTO bean objects.

Is SQLException the right Exception for my error ?

Yes, SQLException is the right exception, but as mentioned above the requests should be filtered in the top layers before reaching the DAO or hitting database. Also, you need to note the below points:

(1) Your exception logging is not proper, i.e., using e.printStackTrace() is not correct, rather use logging frameworks like log4j to log the exception details.

(2) After catching the SQLException, the best practice is to wrap into an appropriate BusinessException and throw it back to the caller with a meaningful error message to the User Interface. If your application just a backend service/process then you can simply log the SQLException details into a file using log4j (depending upon the business requirement) and then collect the statistics of such exceptions to identify the root cause.