网关 Spring Cloud Gateway 统一全局异常处理,那些年Java面试官常问的知识点
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\": \"系统异常,请联系管理员\"}";
DataBufferFactory bufferFactory = response.bufferFactory();
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
return response.writeWith(Mono.just(bufferFactory.wrap(errorMessage.getBytes(StandardCharsets.UTF_8))));
});
}
}
这段代码实现了一个全局异常处理的过滤器,当后端服务发生错误时,会返回一个统一的JSON格式的错误信息。这种做法有助于提升用户体验,并简化了系统对异常的处理流程。在实际使用时,你可以将此类注册为一个Bean,以便Spring Cloud Gateway能够自动发现并应用它。
评论已关闭