java—使用SpringREST模板处理超时和其他io异常的常用方法

bjp0bcyl  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(341)

问题
我有大约40个方法使用restemplate进行http调用。此时,我决定创建一个错误处理程序,将restemplateexceptionMap到我自己的异常(例如myapplicationrestexception)。
深思熟虑的方法
用try/catch Package 所有通话
1.1缺点:应该更新全部40种方法。很容易忘记那些尝试新方法的人
org.springframework.web.client.responseerrorhandler
2.1缺点:由于某些原因,它只捕获具有statuscode的异常!=无效的。所以它不能处理超时。
引入一个新的方面,它将捕获所有restemplateexception并正确处理它们。它解决了以前解决方案的所有缺点,但我始终将实现方面作为最后的选择。
有没有更好的解决办法?

t9aqgxwy

t9aqgxwy1#

最后我想到了方面:

@Aspect
@Component
public class RestCallsExceptionHandlingAspect {

    @AfterThrowing(pointcut = "execution(* eu.mypackage.RestClient.*(..))", throwing = "e")
    public void handle(Exception e) throws Throwable  {
        if (e instanceof RestClientException) {
            if (e instanceof HttpStatusCodeException) {
                if (((HttpStatusCodeException)e).getStatusCode().is4xxClientError()) {
                    throw new TranslatableException(e, ValidationErrorGroup.COMMUNICATION_ERROR, CommonErrorCode.CLIENT_ERROR.name());
                } else {
                    throw new TranslatableException(e, ValidationErrorGroup.COMMUNICATION_ERROR, CommonErrorCode.SERVER_ERROR.name());
                }
            } else {
                throw new TranslatableException(e, ValidationErrorGroup.COMMUNICATION_ERROR, CommonErrorCode.CORE_IO_ERROR.name());
            }
        }
        throw e;
    }
}

相关问题