在Java中进行数据库异常处理的更好方法

Zaw*_* oo 3 java database jdbc

哪一个会更好:针对那种情况的ErrorCode或Exception?

我一直在看这两种错误处理技术.我不知道每种技术的缺点和优点.

public void doOperation(Data data) throws MyException {
    try {
        // do DB operation
    } catch (SQLException e) {
        /* It can be ChildRecordFoundException, ParentRecordNotFoundException
         * NullValueFoundException, DuplicateException, etc..
         */
        throw translateException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

public void doOperation(Data data) throws MyException {
    try {
        // do DB operation
    } catch (SQLException e) {
        /* It can be "CHILD_RECORD_FOUND, "PARENT_RECORD_NOT_FOUND"
         * "NULL_VALUE_FOUND", "DUPLICATE_VALUE_FOUND", etc..
         */
        String errorCode = getErrorCode(e);
        MyException exc = new MyException();
        exc.setErrorCode(errorCode);
        throw exc;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于第二种方法,错误代码检索表单配置文件.我们可以添加Error Code基于SQL Vender Code.

SQL_ERROR_CODE.properties

#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED
Run Code Online (Sandbox Code Playgroud)

方法1的调用者客户端

    try {

    } catch(MyException e) {
        if(e instanceof ChildRecordFoundException) {
            showMessage(...);
        } else if(e instanceof ParentRecordNotFoundException) {
            showMessage(...);
        } else if(e instanceof NullValueFoundException) {
            showMessage(...);
        } else if(e instanceof DuplicateException) {
            showMessage(...);
        }
    }
Run Code Online (Sandbox Code Playgroud)

方法2的呼叫者客户端

    try {

    } catch(MyException e) {
        if(e.getErrorCode().equals("CHILD_RECORD_FOUND")) {
            showMessage(...);
        } else if(e.getErrorCode().equals("PARENT_RECORD_NOT_FOUND") {
            showMessage(...);
        } else if(e.getErrorCode().equals("NULL_VALUE_FOUND") {
            showMessage(...);
        } else if(e.getErrorCode().equals("DUPLICATE_VALUE_FOUND") {
            showMessage(...);
        }
    }
Run Code Online (Sandbox Code Playgroud)

art*_*tol 6

我建议使用Spring的JDBCTemplate.它会将大多数现有数据库的异常转换为特定的未经检查的异常,例如DataIntegrityViolationException.它还将在消息中包含原始SQL错误.