Skip to content

Commit

Permalink
[#38]feat: gateway 뒤에 있는 서버가 죽었을 경우 예외 처리
Browse files Browse the repository at this point in the history
  • Loading branch information
SongGwanSeok committed Nov 5, 2024
1 parent 011be8a commit f60224e
Showing 1 changed file with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange)
.onErrorResume(ConnectException.class, throwable -> handleConnectException(exchange));
}

private Mono<Void> 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));
}
}

0 comments on commit f60224e

Please sign in to comment.