From f60224e04772b8a054714b51baac7192a5942aea Mon Sep 17 00:00:00 2001 From: GS_song98 <20003204@sju.ac.kr> Date: Tue, 5 Nov 2024 19:17:08 +0900 Subject: [PATCH] =?UTF-8?q?[#38]feat:=20gateway=20=EB=92=A4=EC=97=90=20?= =?UTF-8?q?=EC=9E=88=EB=8A=94=20=EC=84=9C=EB=B2=84=EA=B0=80=20=EC=A3=BD?= =?UTF-8?q?=EC=97=88=EC=9D=84=20=EA=B2=BD=EC=9A=B0=20=EC=98=88=EC=99=B8=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ServerConnectionExceptionFilter.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/soma/edupigateway/filter/ServerConnectionExceptionFilter.java diff --git a/src/main/java/soma/edupigateway/filter/ServerConnectionExceptionFilter.java b/src/main/java/soma/edupigateway/filter/ServerConnectionExceptionFilter.java new file mode 100644 index 0000000..22fd240 --- /dev/null +++ b/src/main/java/soma/edupigateway/filter/ServerConnectionExceptionFilter.java @@ -0,0 +1,34 @@ +package soma.edupigateway.filter; + +import java.net.ConnectException; +import java.nio.charset.StandardCharsets; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +@Component +public class ServerConnectionExceptionFilter implements GlobalFilter { + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + return chain.filter(exchange) + .onErrorResume(ConnectException.class, throwable -> handleConnectException(exchange)); + } + + private Mono handleConnectException(ServerWebExchange exchange) { + // 응답 설정 + exchange.getResponse().setStatusCode(HttpStatus.SERVICE_UNAVAILABLE); + + String responseBody = "The backend server is unavailable."; + + DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory(); + DataBuffer buffer = dataBufferFactory.wrap(responseBody.getBytes(StandardCharsets.UTF_8)); + + return exchange.getResponse().writeWith(Mono.just(buffer)); + } +}