提问人:joseluisbz 提问时间:1/20/2023 更新时间:1/20/2023 访问量:36
Java 8,可选。引发异常,并重新引发异常,防止 null
Java 8, Optional. throwing Exceptions, and Re-throwing exceptions, preventing null
问:
我感到困惑(缺乏理解),试图将我的代码的某些部分翻译成 Java 8。Optional
第一个示例模拟代码
private void privateMethodOne(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<CustomResponseDto> responseEntity;
try {
responseEntity = callWebClientRequestOne();
} catch (Exception e) {
RuntimeException ex = new CustomClientException(customRequesDto, e.getMessage());
log.error(ex.getMessage());
throw ex;
}
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
}
在第一个示例模拟代码中,我想将这一行减少到一行中,使用(如果可能的话)Optional
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
如何在单行中做同样的事情?
第二个示例模拟代码
private void privateMethodTwo(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<byte[]> responseEntity = null;
try {
responseEntity = callWebClientRequestTwo();
} catch (Exception e) {
mapExceptions.put(customRequesDto, e.getMessage());
}
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
// continue the executions
}
第二个示例模拟代码,我想将这一行减少到一行中,使用(如果可能的话)Optional
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
如何在单行中执行相同的操作?
答: 暂无答案
评论