Spring Cloud Gateway变更响应



我有一个应用程序(app1),它通过Spring云网关向另一个应用程序(app2)发送请求。app2上的一些端点尚未准备好,因此app2像往常一样返回404(未找到),但我想将404更改为501(未实现)。有什么办法吗?我所做的如下:

spring.cloud.gateway.routes[0].id=app2  
spring.cloud.gateway.routes[0].uri=lb://app2
spring.cloud.gateway.routes[0].predicates[0]=Path=/1/app2/get/endPoint1/**,/1/app2/get/endPoint2/**,/1/app2/get/endPoint3/**,/1/app2/get/endPoint4/**
spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1

endPoint1和endPoint2已经实现,但endPoint3和endPoint4没有实现。
我已经实现了以下过滤器修改404到501,但状态总是200 (OK),即使对于未实现的方法,但app1上的消息是针对未实现的方法(实现的方法没有问题)。

{
"code": 404,
"type": "Not Found",
"message": "{"timestamp":"2022-07-07T16:15:12.185+00:00","status":404,"error":"Not Found","message":"No message available","path":"/app2/endPoint3"}"  
}

如何捕获404并将其修改为501?

@Component
public class GatewayGlobalExceptionHandler implements GlobalFilter, Ordered {
@Override
public int getOrder() {
return 100;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse originalResponse = exchange.getResponse();
HttpStatus status = exchange.getResponse().getStatusCode();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
if (body instanceof Flux) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.map(dataBuffer -> {
// probably i should reuse buffers 
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
//BUT Content is not what i need.
return bufferFactory.wrap(uppedContent);
}));
}
return super.writeWith(body); // if body is not a flux. never got there.
}
};
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
}

修改错误消息,我已经实现了Post-GlobalFilter。这样我就有机会修改状态。此外,我得到404未实现的方法和200后globalfilter实现的方法。

@Configuration
public class LoggingGlobalFiltersConfigurations {
final Logger logger =
LoggerFactory.getLogger(
LoggingGlobalFiltersConfigurations.class);
@Bean
public GlobalFilter postGlobalFilter() {
return (exchange, chain) -> {
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
HttpStatus status = exchange.getResponse().getStatusCode();
//MAKE MODIFICATION HERE
}));
};
}
}

相关内容

  • 没有找到相关文章

最新更新