Spring cloud gateway 自定义返回值(包括异常捕获自定义信息返回)


Hi ~ 小老弟开始转公众号啦,欢迎大家来指点迷津呀
在这里插入图片描述

  • 在使用spring cloud微服务架构的时候,我们一般都会用到spring cloud gateway作为网关去做一些权限检验、请求拦截、转发等功能。 当我们需要自定义返回信息的时候,我们需要对网关的默认的响应信息进行一定的修改,以符合我们的要求。

版本信息:

spring-cloud-starter-gateway:3.0.3
spring-boot-starter:2.5.2
hutool-all:5.5.8

1. 正常返回

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
     // 例如返回自定义json格式数据
     JSONObject result = JSONUtil.createObj();
	 byte[] bytes = JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8);
     ServerHttpResponse response = exchange.getResponse();
     response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
     DataBuffer buffer = response.bufferFactory().wrap(bytes);
     return response.writeWith(Mono.just(buffer));
}

2. 自定义异常返回

@Slf4j
@Component
public class GatewayExceptionHandler extends DefaultErrorWebExceptionHandler {

    @ConditionalOnMissingBean
    @Bean
    public ErrorProperties errorProperties() {
        return new ErrorProperties();
    }

    @Autowired
    public GatewayExceptionHandler(ErrorAttributes errorAttributes,
                                   WebProperties.Resources resources,
                                   ErrorProperties errorProperties,
                                   ApplicationContext applicationContext) {
        super(errorAttributes, resources, errorProperties, applicationContext);
        ServerCodecConfigurer serverCodecConfigurer = applicationContext.getBean(ServerCodecConfigurer.class);
        super.setMessageReaders(serverCodecConfigurer.getReaders());
        super.setMessageWriters(serverCodecConfigurer.getWriters());
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
    	// 从这里可以拿到异常信息,后续可以根据不同异常进行不同的返回
        Throwable throwable = super.getError(request);
        Map<String, Object> result = JSONUtil.createObj();
        return result;
    }

    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
    	// errorAttributes 相当于自定义返回值对象,这里需要有状态码,以表名请求是否合理
        return (int) errorAttributes.get("code");
    }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐