[英]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.