gpt4 book ai didi

java - 异常传播

转载 作者:行者123 更新时间:2023-12-02 10:09:09 25 4
gpt4 key购买 nike

如何将对下游服务的调用中引发的异常传播给调用方方法?

我有一个服务可以计算一些内容并在出现错误时抛出异常:

{
"timestamp": "2019-03-12T08:21:05.316+0000",
"status": 500,
"error": "Internal Server Error",
"message": "VAKUUTUSVUOSI.MAKSUEHTO is null or not numeric. Can't be added to due date.",
"path": "/rules/yk32/deducePaymentDueDate"
}

但调用服务显示此异常:

{
"timestamp": "2019-03-12T08:30:22.912+0000",
"status": 500,
"error": "Internal Server Error",
"message": "500 null",
"path": "/calculation/annual/payment"
}

如何让调用者方法也显示服务抛出“/rules/yk32/deducePaymentDueDate”而不是“内部服务器错误”的消息?

调用方式:

LocalDate paymentDueDate = ykServiceAdapter.yk32DeducePaymentDueDate(requestDTO);

调用ykServiceadapter中的函数:

public LocalDate yk32DeducePaymentDueDate(Yk32RequestDTO requestDTO) {
ResponseEntity<LocalDate> re;
HttpEntity<?> entity = new HttpEntity<>(requestDTO);
try {
re = getRestTemplate().exchange(
buildServiceUrl(externalServiceConfig, RULE_YK32, DEDUCE_PAYMENT_DUEDATE),
HttpMethod.POST, entity,
new ParameterizedTypeReference<LocalDate>() {
});
return re.getBody();

} catch (HttpClientErrorException ex) {
if (HttpStatus.NOT_FOUND.equals(ex.getStatusCode())) {
return null;
} else {
throw ex;
}
}
}

最佳答案

您正在通过 HTTP 处理两个独立的上下文。

这意味着由 yk32DeducePaymentDueDate 生成的 Exception转换HTTP 500 响应,其中 < strong>可能表示Exception消息用作响应正文。

显然,由于原始的ExceptionHTTP调用期间丢失,RestTemplate只能创建一个HttpClientErrorException 基于 HTTP 状态代码

HttpClientErrorException.BadRequest
HttpClientErrorException.Conflict
HttpClientErrorException.Forbidden
HttpClientErrorException.Gone
HttpClientErrorException.MethodNotAllowed
HttpClientErrorException.NotAcceptable
HttpClientErrorException.NotFound
HttpClientErrorException.TooManyRequests
HttpClientErrorException.Unauthorized
HttpServerErrorException.InternalServerError
HttpServerErrorException.NotImplemented
...

在您的情况下,实例化的Exception

public static class InternalServerError extends HttpServerErrorException {
InternalServerError(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
super(HttpStatus.INTERNAL_SERVER_ERROR, statusText, headers, body, charset);
}
}
<小时/>

只有 Exception 消息可能会被恢复(如果它已在响应正文中传输)。

您可能想要研究自定义的 ResponseErrorHandler,您可以在其中检查完整的 HTTP 响应并做出相应的 react 。

关于java - 异常传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55117190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com