吃透Spring Cloud gateway自定义错误处理Handler
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class CustomErrorHandler implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse response = exchange.getResponse();
// 假设我们要处理的特定错误状态码是 HttpStatus.NOT_FOUND
if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
// 自定义错误信息
String message = "Sorry, the resource you requested was not found.";
byte[] bytes = message.getBytes(exchange.getResponse().getCharset());
DataBufferFactory bufferFactory = response.bufferFactory();
response.setStatusCode(HttpStatus.NOT_FOUND);
response.getHeaders().set("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(bufferFactory.wrap(bytes)));
}
// 如果不是我们处理的错误,则继续传递给其他过滤器处理
return chain.filter(exchange);
}
}
这段代码定义了一个CustomErrorHandler
类,实现了GlobalFilter
接口。它检查响应状态码是否为HttpStatus.NOT_FOUND
,如果是,则返回自定义的错误信息。如果不是HttpStatus.NOT_FOUND
状态码,则调用过滤器链的下一个过滤器。这是一个简单的错误处理示例,实际应用中可能需要更复杂的错误处理逻辑。
评论已关闭