为catch块内的对象添加日志记录



我想以这样的方式处理代码中的异常:在对象处理过程中,如果出现异常,那么在catch块中,我想记录导致该异常的对象。

我代码:

public String handleRequest(KinesisEvent kinesisEvent, Context context) {
try {
List<myObj> allObj = kinesisEvent.getRecords().stream()
.map(it -> it.getKinesis().getData())
.filter(ByteBuffer::hasArray)
.map(byteBuffer -> new String(byteBuffer.array(), StandardCharsets.UTF_8))
.map(dataInString -> jsonSerDe.fromJson(dataInString, myObj.class))
.collect(Collectors.toList());
//some code
}
catch (Exception ex) {
// Here I want to log out the particular `dataInString` string 
// that caused the exception to be trigerred. 
logger.error("Parsing input to myObj failed: {}", ex.getMessage(), ex);

}

try/catch块在map函数内工作

public String handleRequest(KinesisEvent kinesisEvent, Context context) {
try {
List<myObj> allObj = kinesisEvent.getRecords().stream()
.map(it -> it.getKinesis().getData())
.filter(ByteBuffer::hasArray)
.map(byteBuffer -> new String(byteBuffer.array(), StandardCharsets.UTF_8))
.map(dataInString -> {
try {
return jsonSerDe.fromJson(dataInString, myObj.class);
}
catch (Exception ex){
logger.error("Parsing input to myObj failed inside stream : {}", dataInString);
//throw new RuntimeException("problem string: " + dataInString); //or your custom exception class
}
})
.collect(Collectors.toList());
//some code
}
catch (Exception ex) {
// Here I want to log out the particular `dataInString` string
// that caused the exception to be trigerred.
logger.error("Parsing input to myObj failed: {}", ex.getMessage(), ex);
}
}

你能试试这个吗?

最新更新