JdbcTemplate.execute() 方法可以抛出的所有异常
All the exceptions that can be thrown by JdbcTemplate.execute() method
如何找出 JdbcTemplate.execute()
方法调用可以抛出哪些异常。我知道它会抛出 DataAccessException
。但是由于 DataAccessException
是抛出的实际异常的父级 class,所以这成为一个非常宽泛的陈述。
例如,它抛出 BadSqlGrammarException
这是子 class。我知道我可以在源代码中找到它,但我想知道是否有列表或某种方法可以找到它,加上从源代码中推断可能会导致问题。原因是要捕获异常,以便我可以记录它们并适当地通知用户。那么,我怎样才能准确地找出抛出的异常呢?我应该这样做还是捕获 DataAccessException
并记录其消息就足够了?
您可以捕获父异常并使用原始代码或实用程序库之一来找到异常的根本原因。
下面的原始代码示例,从 catch 块调用。
应始终记录异常和消息的根本原因。通常有一个集中的通用异常处理程序,仅在一个地方记录异常(例如在 Spring 应用程序中,我们使用 @ControllerAdvice
private static Throwable findSpecificCause(Throwable throwable) {
Throwable rootCause = getRootCause(throwable);
return (rootCause != null ? rootCause : throwable);
}
private static Throwable getRootCause(Throwable throwable) {
if (throwable == null) {
return null;
}
Throwable rootCause = null;
Throwable cause = throwable.getCause();
while (cause != null && cause != rootCause) {
rootCause = cause;
cause = cause.getCause();
}
return rootCause;
}
您还可以考虑使用 Apache 的通用语言 ExceptionUtils、Spring NestedExceptionUtils 或来自 Guava 的库
另见 link :Exception Root Cause
如何找出 JdbcTemplate.execute()
方法调用可以抛出哪些异常。我知道它会抛出 DataAccessException
。但是由于 DataAccessException
是抛出的实际异常的父级 class,所以这成为一个非常宽泛的陈述。
例如,它抛出 BadSqlGrammarException
这是子 class。我知道我可以在源代码中找到它,但我想知道是否有列表或某种方法可以找到它,加上从源代码中推断可能会导致问题。原因是要捕获异常,以便我可以记录它们并适当地通知用户。那么,我怎样才能准确地找出抛出的异常呢?我应该这样做还是捕获 DataAccessException
并记录其消息就足够了?
您可以捕获父异常并使用原始代码或实用程序库之一来找到异常的根本原因。 下面的原始代码示例,从 catch 块调用。 应始终记录异常和消息的根本原因。通常有一个集中的通用异常处理程序,仅在一个地方记录异常(例如在 Spring 应用程序中,我们使用 @ControllerAdvice
private static Throwable findSpecificCause(Throwable throwable) {
Throwable rootCause = getRootCause(throwable);
return (rootCause != null ? rootCause : throwable);
}
private static Throwable getRootCause(Throwable throwable) {
if (throwable == null) {
return null;
}
Throwable rootCause = null;
Throwable cause = throwable.getCause();
while (cause != null && cause != rootCause) {
rootCause = cause;
cause = cause.getCause();
}
return rootCause;
}
您还可以考虑使用 Apache 的通用语言 ExceptionUtils、Spring NestedExceptionUtils 或来自 Guava 的库
另见 link :Exception Root Cause