我有一个从DB中查找记录并返回一个可选记录的服务,然后取决于记录是否存在,我需要将记录消息推送到kafka,以下是我的代码:
public void process(final String message) throws ProcessorError {
Optional<User> saved = userService.save(message);
saved.ifPresent(theUser -> kafkaProducer.produce(message));
}然而,kafkaProducer可能会抛出一个EncryptionError,它是ProcessorError的子类,所以IntelliJ对此并不满意。根据它的建议,我必须将代码更改为:
saved.ifPresent(
theUser ->
{
try {
kafkaProducer.produce(message);
} catch (EncryptionError encryptionError) {
encryptionError.printStackTrace();
}
});但是现在我不想打印stacktrace,我只想重新抛出它,所以我再次将它更改为:
saved.ifPresent(
theUser ->
{
try {
kafkaProducer.produce(message);
} catch (EncryptionError encryptionError) {
throw encryptionError;
}
});然而,IntelliJ又不高兴了,建议我用另一个try/catch来包围那个抛出语句,我怎么才能在没有讨厌的编译器的情况下抛出它呢?
感谢每个人的回复,但我确实需要将其保留为EncryptionError而不是RuntimeException,并且我不喜欢在抛出encryptionError时使用另一次尝试/捕获,我是不是又回到了原来的方式:
if (saved.isPresent()) {
kafkaProducer.produce(message);
}发布于 2020-02-27 04:32:52
假设EncryptionError是一个受控异常,你可以将它包装在一个非受控异常中。
saved.ifPresent(
theUser ->
{
try {
kafkaProducer.produce(message);
} catch (EncryptionError encryptionError) {
throw new RuntimeException(encryptionError);
}
});发布于 2020-02-27 04:34:53
我认为EncryptionError是checked exception的一个子类型。所以只需要用RuntimeException包装它,你就完成了。像这样:try { .... } catch (EncryptionError e) { throw new RuntimeException(e.getMessage()); }
发布于 2020-02-27 07:56:44
正如已经提到的,将检查异常包装为未检查异常是可行的,你不需要在签名方法anymore.
throw RuntimeException.比throw MessageProducingException更好
总结一下我上面说的话:
// Getting rid of throws signature
public void process(final String message) {
userService.save(message)
.ifPresent(user -> produceMessage(message);
}
// encapsulated produce method, will deal with exception wrapping
private void produceMessage(Message message) {
try {
kafkaProducer.produce(message);
} catch (EncryptionError encryptionError) {
// creating and using custom domain-specic exception here, pick up a proper name
throw new MessageProducingException(encryptionError);
}
}进一步的改进步骤可以是向您的kafkaProducer添加另一个抽象级别,并使用更多的缩写producer。
https://stackoverflow.com/questions/60421970
复制相似问题