我有一个界面:
public interface ThirdPartySystemCaller {
void sendRequest(String request) throws ThirdPartySystemException;
}
和实现:
@Slf4j
@Service
public class ThirdPartySystemCallerImpl implements ThirdPartySystemCaller {
@Override
public void sendRequest(String request) throws ThirdPartySystemException {
if (request == null) throw new ThirdPartySystemException();
log.info("send: {}", request);
}
}
我有一个 CryptoService 女巫可以签署请求:
public interface CryptoService {
String signRequest(String request) throws CryptoException;
}
及其实现:
@Slf4j
@Service
public class CryptoServiceImpl implements CryptoService {
@Override
public String signRequest(String request) throws CryptoException {
if (request.length() > 100) throw new CryptoException(); //just for example
return "signed " + request;
}
}
现在,我可以使用这些服务:
String signedRequest = cryptoService.signRequest("Hello");
thirdPartySystemCaller.sendRequest(signedRequest);
但我每次都需要调用这两个服务。我想创建代理
:
@Slf4j
@Service
public class ThirdPartySystemCallerSignedProxy implements ThirdPartySystemCaller {
private final ThirdPartySystemCaller thirdPartySystemCaller;
private final CryptoService cryptoService;
public ThirdPartySystemCallerSignedProxy(ThirdPartySystemCaller thirdPartySystemCaller, CryptoService cryptoService) {
this.thirdPartySystemCaller = thirdPartySystemCaller;
this.cryptoService = cryptoService;
}
@Override
public void sendRequest(String request) throws ThirdPartySystemException {
String signedRequest = cryptoService.signRequest(request);
thirdPartySystemCaller.sendRequest(signedRequest);
}
}
但我的 ThirdPartySystemCallerSignedProxy
实现 ThirdPartySystemCaller
接口(interface)和 sendRequest
方法仅抛出 ThirdPartySystemException
。但是如果 cryptoService
抛出 CryptoException
我也需要抛出它。
我该怎么做?
我正在考虑进行未经检查的异常,但我需要进行检查。
最佳答案
创建基本异常
您可以创建抽象异常BusinessException
,它可以是ThirdPartySystemException
和CryptoException
的基本异常。现在,您可以定义 sendRequest
方法抛出 BusinessException
,真正的异常取决于给定的问题。
外观
ThirdPartySystemCallerSignedProxy
是一个不好的名字,因为它提醒 Proxy
模式不是您所实现的。本课提醒Facade模式,因为您想为两个不同的接口(interface)创建具有更简单的 API
的统一接口(interface)。在这种情况下,如果 CryptoException
将被抛出到 ThirdPartySystemException
中,您可以包装它,或者创建基本异常并在方法中声明它。更好的是,您不知道会抛出哪种异常,但可以肯定它会是 BusinessException
。
责任链
许多图书馆使用 Chain of Responsibility
处理请求 -> 响应
通信。如果需要,所有链单元都需要在声明中实现相同的接口(interface)和基本异常。您可以在 bean 定义中构建链。它更容易维护,因为所有单元都是独立的,不需要像Facade
中那样相互了解。您可以在 @Bean
方法声明中构建链,如下所示:
@Bean
public ServiceChainCell thirdPartyCaller() {
CryptoService crypto = cryptoService();
ThirdPartySystemCaller caller = thirdPartySystemCaller();
// Create chain
crypto.setNext(caller);
return crypto;
}
setNext
方法来自 ServiceChainCell
接口(interface),该接口(interface)还应该具有 sendRequest(String request)
方法。
详细了解这些模式,您将找到最适合您的解决方案。
关于java - 我无法转发代理类中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418558/