处理改变DB中某些数据的api调用。我试图在api中提供有意义的消息,以防JPA Layer中出现异常。在任何sql查询运行失败时,我从JPA获得DataIntegrityViolationException,它不包含失败的确切原因。因此,我从中提取SQLException,然后使用错误消息进行响应。
private String getSQLExceptionMessage(DataIntegrityViolationException e) {
Throwable nextException = e.getCause();
while (!nextException.getClass().equals(SQLException.class) && nextException.getCause() != null
&& !nextException.getClass().equals(nextException.getCause().getClass())) {
nextException = nextException.getCause();
}
return nextException.getMessage();
}
有没有更好的方法呢?
答案 0 :(得分:2)
Spring中有一个实用程序类Windows10
,您可以使用NestedExceptionUtils
方法来获取任何异常的“根”原因。
关于错误处理 - 您可以为getMostSpecificCause
实现custom exception handler,从根本原因中提取约束名称,对其进行分析并为用户创建相应的消息。
答案 1 :(得分:0)
是的,您可以在 Spring 中使用 NestedExceptionUtils
来获取任何异常的根课程。下面的示例代码
try {
//your code
} catch (DataIntegrityViolationException e){
throw new DataIntegrityViolationException(NestedExceptionUtils.getMostSpecificCause(e).getMessage());
}