null作为具有业务含义的一部分,不断抛出
1.service中抛出特定的IllegalArgumentException异常
JsonObject responseBody = !Objects.requireNonNull(jsonObject).get("responsebody").toString().equals("null") ? jsonObject.get("responsebody").getAsJsonObject():null;
if (null == responseBody ) {
throw new IllegalArgumentException(String.format("获取用户%s信息出错。", erp));
}
if (null == responseBody.get("realName") || (responseBody.get("realName") instanceof JsonNull)||"null".equalsIgnoreCase(responseBody.get("realName").toString())){
throw new IllegalArgumentException(String.format("获取用户%s信息出错。", erp));
}
2.上层调用方法封装,并抛出IllegalArgumentException异常
public static Receiver createReceiver(NotifyMethod notifyMethod, String code) throws IllegalArgumentException{
switch (notifyMethod){
case TIMLINE:
return new TimLineReceiver().setErp(code);
case PHONE:
ContactDto phoneUserInfo = contactService.getUserInfo(code);
return new PhoneReceiver().setNumber(phoneUserInfo.getPhone()).setErp(code);
case EMAIL:
ContactDto emailUserInfo = contactService.getUserInfo(code);
return new EmailReceiver().setAddress(emailUserInfo.getEmail());
case OE:
return new OeReceiver().setErp(code);
default:
throw new IllegalArgumentException("未获取到此通知方式对应的Receiver");
}
}
3.再上层封装,处理流中对特定异常处理,返回null对象,再进行filter
private Function<String,Receiver> receiverGetter(NotifyMethod notifyMethod){
return erp -> {
try {
return ReceiverFactory.createReceiver(notifyMethod, erp);
} catch (IllegalArgumentException e) {
log.error("获取联系人异常:", e);
return null;
}
};
}
public void process(ProcessContext<NotificationModel> context) {
NotificationModel notificationModel = context.getProcessModel();
// 不同的通知方式->不同的通知模板->不同的接收人对象
notificationModel.getAlarmNotificationMap().forEach((notifyMethod, alarmNotificationDto) -> {
Set<String> erps = ErpListFactory.getErps(notificationModel);
List<Receiver> receivers = erps
.stream()
.map(erp -> receiverGetter(notifyMethod).apply(erp))
.filter(Objects::nonNull)
.collect(Collectors.toList());
alarmNotificationDto.setReceivers(receivers);
log.info("消息ID:[{}] @@{}通知方式补齐通知接收人信息完毕,接收人{}", context.processModel.messageId, notifyMethod, JsonUtils.toJSONString(receivers));
});
}
原创:做时间的朋友