我想以这样的方式处理代码中的异常:在处理对象期间,如果出现异常,那么我想在 catch block 中记录导致此异常的对象。
我的代码:
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 block 在 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);
}
}
你能试试这个吗?
关于java - 为 catch block 内的对象添加日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72232503/