java - 为 catch block 内的对象添加日志记录

标签 java amazon-web-services exception try-catch

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

相关文章:

java - 如何创建返回元素和相关元素数组的 JPA 查询

amazon-web-services - 如何在 API 网关中上传大于 5mb 的大文件?使用无服务器和 nodejs

javascript - 从另一个未被调用的 Lambda 函数中调用 Lambda 函数

java - 您对 Java bean 和数据库中字段名称命名约定之间差距的看法

java - eclipse可以调试或运行一个项目中的两个程序

Java编码: why the output is always the same?

amazon-web-services - 创建表不会反射(reflect)在 DynamoDB 控制台中

java - 烟灰、身份 stmts 和异常处理期间的控制流

scala - 如何检查构造函数参数并抛出异常或在 Scala 中的默认构造函数中进行断言?

java - Junit (3.8.1) 测试是否抛出异常(在单元测试中有效,添加到 testSuite 时失败)