Home > Blockchain >  Adding logging for an object inside catch block
Adding logging for an object inside catch block

Time:05-18

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);
            
        }

CodePudding user response:

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?

  • Related