Spring Cloud Gateway过滤器精确控制异常返回(实战,完全定制返回body)
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
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;
 
import java.nio.charset.StandardCharsets;
 
public class CustomErrorFilter implements GlobalFilter {
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 注意:这里的逻辑需要根据实际情况进行定制
        if (/* 检查条件,例如判断响应状态码是否为500 */ false) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            // 定制返回的body内容
            String body = "{\"message\":\"服务器内部错误\"}";
            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            // 重要:这里需要指明返回的content type 为 application/json
            response.getHeaders().setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }
}这段代码定义了一个自定义的错误过滤器,用于在Spring Cloud Gateway中处理特定的异常情况并返回完整定制的响应体。在实际使用时,需要根据具体需求修改检查条件和返回的body内容。
评论已关闭