'Adding logging for an object inside catch block
I want to handle exceptions in code in a way that during the processing of an object if an exception arises, then in the catch block I want to log the object that caused this exception.
My code:
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);
            
        }
Solution 1:[1]
try/catch block works inside map function.
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);
    }
}
can you try this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 

 amazon-web-services
amazon-web-services