2012-07-06 55 views
1

我有使用Hibernate(3.6.9.Final)的Spring MVC(3.1.1.RELEASE)应用程序。 其配置了Log4j。无法捕捉Spring MVC中的org.hibernate.util.JDBCExceptionReporter异常

log4j.category.org.hibernate.SQL=DEBUG 
log4j.logger.org.hibernate.event.def.AbstractFlushingEventListener=OFF 

当我尝试添加一行到我的表,如果该字段的长度超过了最大大小,在日志中我可以看到这个异常:

hibernateTemplate.merge(ba); 

在日志:

2012-07-06 15:22:35,546 ERROR [org.hibernate.util.JDBCExceptionReporter] - <ERROR: value `too long for type character varying(70)>` 

但在另一方面,在我的代码,所有我能赶上这是DataAccessException的例外:

Could not execute JDBC batch update; SQL [insert into T_MYTABLE (BA_NUMBER, USR_ID, BA_ID) values (?, ?, ?)]; nested exception is org.hibernate.exception.DataException: Could not execute JDBC batch update"} 

这不是我想要的例外。

您是否知道我可以从我的应用程序中的日志文件中获取消息?

我试过捕捉HibernateException但没有成功。

+1

您是否尝试过检查DataAccessException上的exception.getCause()? – Manish 2012-07-06 08:27:04

+0

我刚刚尝试过使用getCause(),但我刚刚得到这个:“无法执行JDBC批量更新不能执行JDBC批量更新”}“ – guigui42 2012-07-06 08:38:45

+0

嗨guigui42,您是否设法捕获JDBCExceptionReporter记录的异常。提交批处理uupdates。我面临类似的问题。 – 2016-01-19 09:55:20

回答

0

我遇到了同样的问题。以下是我筛选完所有各种包装和无用的通用错误后所得出的结果。 似乎应该有更好的方法。我感觉这是脆弱的,并且是特定实现的。

@ExceptionHandler(DataAccessException.class) 
@ResponseBody 
public ErrorResponse handleDataAccessException(DataAccessException e, HttpServletResponse response) { 
    String errorString = null; 
    Throwable t = e.getCause();  
    if(t instanceof PersistenceException) { 
     t = t.getCause(); 
     if(t instanceof ConstraintViolationException) { 
      t = t.getCause(); 
      if(t instanceof BatchUpdateException) {    
       SQLException sqlException = null; 
       sqlException = ((SQLException) t).getNextException(); 
       if(sqlException instanceof PSQLException) { 
        errorString = ((PSQLException)sqlException).getServerErrorMessage().toString(); 
        log.error("Caught exception: type=\"" + sqlException.getClass().getSimpleName() + " " + errorString); 
       } 
      } 
     } 
    } 
    response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); 
    ErrorResponse errorResponse = new ErrorResponse(); 
    Set<ResultCode> resultCodes = new HashSet<ResultCode>(); 
    resultCodes.add(ResultCode.SERVER_ERROR); 
    errorResponse.setResultCodes(resultCodes); 
    return errorResponse; 
}