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.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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().setContentType(MediaType.APPLICATION_JSON);
// 自定义错误信息
String errorMessage = "{\"message\":\"系统异常,请联系管理员\"}";
byte[] bytes = errorMessage.getBytes(StandardCharsets.UTF_8);
DataBufferFactory bufferFactory = response.bufferFactory();
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response.writeWith(Mono.just(bufferFactory.wrap(bytes)));
});
}
}
然后需要将这个全局过滤器注册到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中的微服务调用出现异常时,Spring Cloud Gateway会使用这个全局过滤器返回自定义的错误信息。
评论已关闭