Spring Cloud Gateway 过滤器中直接返回错误结果信息

Posted 抓手

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Cloud Gateway 过滤器中直接返回错误结果信息相关的知识,希望对你有一定的参考价值。

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.poly.gateway.common.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证过滤器
 *
 * @author 向振华
 * @date 2020/09/16 10:30
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered 

    @Override
    public int getOrder() 
        return 0;
    

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) 
        if (认证通过) 
            return chain.filter(exchange);
         else 
            return errorInfo(exchange, "认证不通过", 1);
        
    

    /**
     * 返回response
     *
     * @param exchange
     * @param message  异常信息
     * @param status   data中的status
     * @return
     */
    public static Mono<Void> errorInfo(ServerWebExchange exchange, String message, Integer status) 
        // 自定义返回格式
        Map<String, Object> resultMap = new HashMap<>(8);
        resultMap.put("status", status == null ? 2 : status);
        resultMap.put("message", StringUtils.isBlank(message) ? "服务异常!" : message);
        resultMap.put("info", null);
        resultMap.put("data", null);
        return Mono.defer(() -> 
            byte[] bytes;
            try 
                bytes = new ObjectMapper().writeValueAsBytes(resultMap);
             catch (JsonProcessingException e) 
                log.error("网关响应异常:", e);
                throw new BusinessException("信息序列化异常");
             catch (Exception e) 
                log.error("网关响应异常:", e);
                throw new BusinessException("写入响应异常");
            
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8.toString());
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        );
    

 

以上是关于Spring Cloud Gateway 过滤器中直接返回错误结果信息的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Spring Cloud Gateway 中添加特定于路由的自定义过滤器

spring cloud gateway 报错 Unable to find GatewayFilterFactory with name

Spring Cloud Gateway 过滤器执行流程(图)

Spring Cloud —— Gateway 服务网关

spring cloud gateway 的执行流程

Spring Cloud Gateway 过滤器中直接返回错误结果信息