我的DAO实现中有以下方法:
@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)
我应该怎么做才能“适当地”处理异常? (我没有兴趣将它扔掉,只吞下它并返回一个空字符串)
最佳答案
您正在明确记录该异常:
logger.error("getResultEntry failed to execute the query due to exception! Return an empty string ", erdae);
如果您不想在日志中看到stacktrace,请删除第二个参数。最好删除整个行,因为这不是错误,并且您已经有一个
info
日志条目。您的代码的执行不会被此异常终止。查找终止原因,该原因位于其他位置,可能与您返回的空字符串无关,也可能与之无关。