我想以一種方式處理代碼中的例外,如果在處理物件期間出現例外,那么在 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);
}
uj5u.com熱心網友回復:
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);
}
}
你能試試這個嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478353.html
