-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #39 from edu-pi/feature/issue38
[#38]feat: gateway 뒤에 있는 서버가 죽었을 경우 예외 처리
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
src/main/java/soma/edupigateway/filter/ServerConnectionExceptionFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} |