繁体   English   中英

如何处理此代码块中的 Null 指针异常?

[英]How to handle Null Pointer Exception in this block of code?

我们在 Spring-Boot 中有以下代码片段:

@Value("${service.image.cloud.host}")
String imgUrl;

private final ImageValidationProperties imageValidationProperties;

public ImageResponse getImageslistFromCloud(String image, Integer cloud) {
    String imageNumber = "0RC";
    String url = imgUrl;
    if (cloud != null) {
        imageNumber = imageValidationProperties.getImagesFromCloud(cloud);
        url = imageValidationProperties.getUrlFromCloud(cloud);
    }
    log.debug("Request images", imageNumber);
    ResponseEntity<ImageResponse> imgResponse = null;
    try {
        RestTemplate template = new RestTemplate();
        imgResponse = template.getForEntity(url.concat(imageNumber).concat(imgUrl), ImageResponse.class);
        return imgResponse.getBody();
    }
    catch (Exception e) {
        log.error("error: {}", e);
        return imgResponse.getBody();
    }

}

我的主管告诉我,它可能会抛出未处理的Null Pointer Exception ,但我不明白如何修复它。 我已经使用try and catch了,所以我不确定 go 会出现什么错误。 有人知道可能出了什么问题吗? 我感谢任何帮助:)

@Value 属性是 null 因为您的 Class 没有 Bean,请尝试使用 @Service、@Component 注释您的 class 甚至使用 @Bean 注释。

如果 template.getForEntity 导致 HTTP 错误(例如,如果找不到资源),您的 catch 块将抛出 NullPointerException。 在这种情况下,imgResponse 仍然是 null 并且您在其上调用 getBody() 方法。 相反,您应该返回 null 或使用 Optional 作为返回类型并返回 Optional.empty()。

您还应该避免捕获非常常见的异常,并更具体地了解您想要捕获的异常。

在 try block中,您实例化imgResponse字段。但是,在catch块中,您使用imgResponse.getBody(); 陈述。 这可能会抛出NullPointerException

避免NullPointerException的一种最佳方法是使用java.util.Optional 这可能会节省在运行时破坏您的代码。

我认为问题出在 catch 块中的 imgResponse.getBody() 上。 在 catch 块中 imgResponse 仍然是 null ,在调用 imgResponse.getBody() 时会抛出 NPE。

另一个地方是:你还需要初始化变量imageValidationProperties,否则它的方法调用会导致null指针异常(imageNumber = imageValidationProperties.getImagesFromCloud(cloud); url = imageValidationProperties.getUrlFromCloud();)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM