我有以下的方法在我的DAO實現:如何拋出EmptyResultDataAccessException?
@Override
public String getResultEntry(String arg1, String key, String date) throws SQLException, IOException {
String res = "";
String sql = buildSQL(arg1, key, date);
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("arg1", arg1);
namedParameters.addValue("id", key);
namedParameters.addValue("date", date);
try {
logger.info("getResultEntry is about to execute the following query:[" + sql + "]");
Blob blob = namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Blob.class);
long blobLength = blob.length();
byte[] bytes = blob.getBytes(1, (int)blobLength);
logger.info("getResultEntry END");
res = convertBytesToString(bytes);
} catch (EmptyResultDataAccessException erdae) {
logger.error("getResultEntry failed to execute the query due to exception! Return an empty string ", erdae);
logger.info("getResultEntry END");
res = "";
}
return res;
}
有時查詢將返回空的結果和EmptyResultDataAccessException
被拋出。我趕上它並返回一個空字符串。但是,我一直看到異常,之後終止執行。
例外:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
at org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:71)
at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject(NamedParameterJdbcTemplate.java:179)
at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject(NamedParameterJdbcTemplate.java:191)
at com.ars.linking.mrretriever.dao.MRRetrieverDAOImpl.getResultEntry(MRRetrieverDAOImpl.java:82)
at com.ars.linking.mrretriever.exec.MRRetriver.processResults(MRRetriver.java:125)
at com.ars.linking.mrretriever.exec.MRRetriver.main(MRRetriver.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
我應該做的 「正確」 處理異常? (我沒有興趣重新拋出它只是吞下它,並返回一個空字符串)
如果我沒有錯,你現在正在做同樣的事情,不是嗎?你已經捕捉到了這個異常,並且你沒有讓它到達前一層。你還想實現什麼? –
只需刪除堆棧跟蹤如果你不想打印它。 –
我看到異常以某種方式潛入並終止流程。我不明白它怎麼會發生(我吞下它)。 – aviad