[Spring Cloud] gateway全局异常捕捉统一返回值
在Spring Cloud Gateway中,可以通过定义一个全局过滤器来捕捉异常,并返回统一的响应格式。以下是一个简单的实现示例:
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
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 GlobalExceptionHandlerFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange).onErrorResume((throwable) -> {
ServerHttpResponse response = exchange.getResponse();
// 设置响应状态码
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
// 设置响应头
response.getHeaders().set("Content-Type", "application/json");
// 创建返回的统一结果对象
String errorResult = "{\"code\": 500, \"message\": \"系统异常,请联系管理员\"}";
// 返回统一结果
DataBufferUtils.write(response.bufferFactory(), errorResult, new NettyDataBufferFactory(ByteBufAllocator.DEFAULT))
.doOnError(err -> DataBufferUtils.release(response.getBody()))
.doOnTerminate(() -> response.close());
return Mono.empty();
});
}
}
然后需要将这个全局过滤器注册到Spring Cloud Gateway中:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public GlobalExceptionHandlerFilter globalExceptionHandlerFilter() {
return new GlobalExceptionHandlerFilter();
}
}
这样配置后,当GatewayFilterChain中的过滤器链发生异常时,GlobalExceptionHandlerFilter
将会捕捉到异常,并返回统一的JSON格式的错误信息。
评论已关闭