Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.example.database.exception;

public class DatabaseException extends OrmException {

public DatabaseException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.example.database.exception;

public class DuplicateKeyException extends OrmException {

public DuplicateKeyException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.example.database.exception;

public class EntityNotFoundException extends OrmException {

public EntityNotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.example.database.exception;

public class EntityValidationException extends OrmException {

public EntityValidationException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.example.database.exception;

import java.sql.SQLException;

public class ExceptionTranslator {

private static final String UNIQUE_VIOLATION_CODE = "23505";

public static OrmException translate(SQLException e, Class<?> entityClass, String sql) {
String sqlState = e.getSQLState();

if (UNIQUE_VIOLATION_CODE.equals(sqlState)) {
String constraintName = extractConstraintName(e);
String message = String.format("Duplicate key violation on entity '%s': unique constraint '%s'",
entityClass != null ? entityClass.getSimpleName() : "unknown",
constraintName);
return new DuplicateKeyException(message);
}

if (sqlState != null && sqlState.startsWith("23")) {
String message = String.format("Database error executing query '%s': %s", sql, e.getMessage());
return new DatabaseException(message);
}

String message = String.format("Database error executing query '%s': %s", sql, e.getMessage());
return new DatabaseException(message);
}

private static String extractConstraintName(SQLException e) {
String message = e.getMessage();
if (message != null && message.contains("unique constraint")) {
int start = message.lastIndexOf("unique constraint \"");
if (start != -1) {
start += "unique constraint \"".length();
int end = message.indexOf("\"", start);
if (end > start) {
return message.substring(start, end);
}
}
}
return "unknown";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.example.database.exception;

public class OrmException extends RuntimeException {

public OrmException(String message) {
super(message);
}
}