오류 처리 및 대체 처리
서비스를 사용할 수 없을 때 점진적으로 기능을 축소할 수 있도록 사용자 지정 오류 처리와 대체 처리 메커니즘을 구현해 보세요.
오류 처리 및 대체 처리은(는) CoddyKit의 무료 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Resilient Error Handling Intro
In a microservices architecture, services can fail. An API Gateway needs robust error handling and fallback mechanisms to ensure the entire system remains stable and user-friendly.
This lesson explores how Spring Cloud Gateway helps you gracefully handle errors and provide alternative responses when backend services are unavailable.
Default Gateway Errors
By default, Spring Cloud Gateway provides generic error responses when a routed service is unreachable or returns an error. These often include standard HTTP status codes (like 500 Internal Server Error, 503 Service Unavailable) and basic JSON.
While functional, these default messages are usually not user-friendly and might expose internal details. Customization is key for a good user experience.
Customizing Error Responses
To improve user experience, we can customize the error responses from the Gateway. This allows us to:
- Provide clear, branded error messages.
- Hide sensitive internal error details.
- Return consistent error formats across all APIs.
Spring Cloud Gateway, being built on Spring WebFlux, allows us to implement custom ErrorWebExceptionHandler components.
Custom Error Handler Example
Let's create a custom error handler that intercepts errors and returns a simplified JSON response. This handler will replace the default error page.
Run this code and try accessing /fail. You'll see our custom message!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
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;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("nonexistent_service", r -> r.path("/fail/**")
.uri("http://localhost:9999")) // Route to a non-existent service
.build();
}
}
@Configuration
@Order(-1) // Ensure this handler runs before default ones
class CustomJsonErrorWebExceptionHandler implements ErrorWebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
String errorBody = "{\"status\":500, \"message\":\"Our service is temporarily unavailable. Please try again!\"}";
DataBuffer buffer = response.bufferFactory().wrap(errorBody.getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(buffer));
}
}Understanding Fallback Mechanisms
A fallback mechanism provides an alternative path or response when a primary service fails or becomes unavailable. Instead of showing a raw error, the Gateway can gracefully degrade by:
- Returning a default response.
- Redirecting to a static error page.
- Calling a dedicated fallback service.
Fallbacks are crucial for resilience and preventing cascading failures.
Gateway Fallback Strategies
Spring Cloud Gateway supports fallbacks primarily through its integration with circuit breakers (like Resilience4j, which we discussed in the previous lesson). When a circuit breaker trips, instead of failing outright, it can invoke a fallback.
A common way to define this fallback is using the setFallbackUri() method within the circuit breaker filter, often pointing to a forward: URI.
Implementing a Simple Fallback Route
The simplest fallback is to forward the request to another URI within the Gateway itself. This can be a static HTML page, a simple Spring controller method, or even another internal route.
The forward: prefix in fallbackUri tells the Gateway to handle the request internally, without making another external HTTP call.
Configuring a Fallback Route
Here's how to configure a route with a fallback. If the /api/** route's backend service fails (e.g., due to a circuit breaker opening), the Gateway will forward the request to our local /fallback endpoint.
Try accessing /api/hello when localhost:9000 is down.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController // For our simple fallback endpoint
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("backend_service", r -> r.path("/api/**")
.filters(f -> f.circuitBreaker(config -> config
.setName("myCircuitBreaker")
.setFallbackUri("forward:/fallback"))) // Fallback URI
.uri("http://localhost:9000")) // A service that might fail
.build();
}
// This method acts as the fallback service
@GetMapping("/fallback")
public String fallback() {
return "Service is currently unavailable. Please try again later!";
}
}Fallback to a Dedicated Service
For more complex scenarios, you might configure fallbackUri to point to a dedicated microservice. This "fallback service" can:
- Serve rich error pages.
- Provide cached or default data.
- Log detailed error information.
This approach centralizes error handling logic and keeps your Gateway configuration cleaner.
Check Your Knowledge
Which of the following are benefits of implementing custom error handling and fallback mechanisms in an API Gateway?
Lesson Summary
In this lesson, we learned the importance of robust error handling and fallback mechanisms in Spring Cloud Gateway. We explored how to:
- Customize default error responses using
ErrorWebExceptionHandler. - Implement simple fallbacks using
setFallbackUri("forward:")with circuit breakers. - Understand the benefits of dedicated fallback services for advanced scenarios.
These techniques are vital for building resilient and user-friendly microservice applications.
자주 묻는 질문
“오류 처리 및 대체 처리” 강의는 무료인가요?
네 — “오류 처리 및 대체 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의 전체를 잠금 해제할 수 있습니다. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 총 4개의 강의가 포함되어 있습니다.
“오류 처리 및 대체 처리”에서 뭘 배우나요?
서비스를 사용할 수 없을 때 점진적으로 기능을 축소할 수 있도록 사용자 지정 오류 처리와 대체 처리 메커니즘을 구현해 보세요. 브라우저에서 직접 실행하는 실습 코드로 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“오류 처리 및 대체 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.