Commit e8c85f2b authored by zhouwei's avatar zhouwei

target 错误时返回对应应答

parent 502c0997
......@@ -347,7 +347,26 @@ public class FailoverGatewayFilterFactory extends AbstractGatewayFilterFactory<F
exchange.getResponse().getHeaders().putAll(clientResponse.headers().asHttpHeaders());
return clientResponse.bodyToMono(DataBuffer.class)
.flatMap(buffer -> exchange.getResponse().writeWith(Mono.just(buffer)))
.flatMap(body -> {
log.info("Target request response: status={}, body={}", responseStatus, body);
DataBuffer body1 = body;
// 检查 HTTP 状态码
if (!responseStatus.is2xxSuccessful()) {
String errorMessage = String.format("Target request failed with status: %s, body: %s",
responseStatus.value(), body);
log.error(errorMessage);
return writeErrorResponse(exchange, HttpStatus.BAD_GATEWAY, errorMessage);
}
try {
return writeResponse(exchange, responseStatus, body);
} catch (Exception e) {
String errorMessage = String.format("Failed to process target response: %s, body: %s",
e.getMessage(), body);
log.error(errorMessage);
return writeErrorResponse(exchange, HttpStatus.BAD_GATEWAY, errorMessage);
}
})
.onErrorResume(throwable -> {
log.info("Error handling response: {}", throwable.getMessage());
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
......@@ -358,6 +377,23 @@ public class FailoverGatewayFilterFactory extends AbstractGatewayFilterFactory<F
});
}
// 辅助方法:写入正常响应
private Mono<Void> writeResponse(ServerWebExchange exchange, HttpStatus status, DataBuffer buffer) {
exchange.getResponse().setStatusCode(status);
return exchange.getResponse().writeWith(Mono.just(buffer));
}
// 辅助方法:写入错误响应
private Mono<Void> writeErrorResponse(ServerWebExchange exchange, HttpStatus status, String message) {
exchange.getResponse().setStatusCode(status);
JSONObject errorResponse = new JSONObject();
errorResponse.put("status", status.value());
errorResponse.put("message", message);
DataBuffer buffer = exchange.getResponse().bufferFactory()
.wrap(errorResponse.toJSONString().getBytes(StandardCharsets.UTF_8));
return exchange.getResponse().writeWith(Mono.just(buffer));
}
private boolean requiresRequestBody(HttpMethod method) {
return method == HttpMethod.POST ||
method == HttpMethod.PUT ||
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment