在Spring Batch应用程序中,我需要改进对StaxEventItemReader的读取错误处理。
到目前为止,我得到了:
public class UserAuthorizationErrorListener extends
ItemListenerSupport<UserAuthorizationType, UserAuthorizationType> {
@Override
public void onReadError(Exception ex) {
ex.printStackTrace();
//TODO how to get the position in the file ? or the current index of the item that raised this exception?
}
}
弹簧配置:
<step id="readFileStep" next="moveFileToFolderDecision">
<tasklet>
<chunk reader="userAuthorizationMultipleResourcesReader"
processor="userAuthorizationItemProcessor"
writer="userAuthorizationCompositeItemWriter"
commit-interval="2">
<listeners>
<listener ref="userAuthorizationErrorListener" />
</listeners>
</chunk>
</tasklet>
</step>
这非常好,我会在发生错误时收到通知。
但我需要提供聪明的错误报告,并提供错误项目的索引。
如何获取此信息? 或者如何在错误发生之前获取正确读取的数量? 或者我如何获得错误的行号和列号?
修改
我得到像这样的堆栈跟踪:
org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[javax.xml.stream.XMLStreamException: ParseError at [row,col]:[20,4]
Message: The element type "Action" must be terminated by the matching end-tag "</Action>".]
at org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException(Jaxb2Marshaller.java:794)
at org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal(Jaxb2Marshaller.java:715)
但是可以避免转换Exception并解析错误消息以获取[row,col]:[20,4]信息吗?
答案 0 :(得分:0)
查看异常的原因(ex.getCause()
)。他们应该提供更多细节。
答案 1 :(得分:0)
最后,我结束了以下解决方案。
由于我已经扩展了StaxEventItemReader
类以满足其他需求,我只是在我的类中添加了以下方法:
public class MyStaxEventItemReader extends StaxEventItemReader<UserAuthorizationType> {
...
/**
* The current index of the item read by the reader.
* <p>
* As the counter is incremented just before the {@link #doRead()} method
* being called, if an exception occurs while reading the next element, the
* index is always correct.
*
* @return The current index of the item read by the reader
*/
public int getCurrentItemCount() {
return super.getCurrentItemCount();
}
}
然后我将读者注入userAuthorizationErrorListener
<bean id="userAuthorizationErrorListener" class="com.my.package.UserAuthorizationErrorListener">
<property name="itemReader" ref="userAuthorizationItemReader" />
</bean>