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

Adding logging for an object inside catch block

我想在代码中处理异常的方式是,如果在处理对象期间出现异常,那么在 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);

    }
}

你能试试这个吗?