0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · Ders

Hataları Ele Alma ve Geri Dönüşler

Hizmetler kullanılamadığında kontrollü bir işlev kaybı sağlamak için özel hata işleme ve geri dönüş mekanizmaları uygulayın.

Hataları Ele Alma ve Geri Dönüşler, CoddyKit'te ücretsiz bir API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) dersidir. Bu, 4 dersinin 3. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“Hataları Ele Alma ve Geri Dönüşler” dersi ücretsiz mi?

Evet — “Hataları Ele Alma ve Geri Dönüşler” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) kursu toplamda 4 dersten oluşur.

“Hataları Ele Alma ve Geri Dönüşler” dersinde ne öğreneceğim?

Hizmetler kullanılamadığında kontrollü bir işlev kaybı sağlamak için özel hata işleme ve geri dönüş mekanizmaları uygulayın. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 3. dersidir.

“Hataları Ele Alma ve Geri Dönüşler” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) dersinde kod yazıp çalıştırabilir miyim?

Evet. Her API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Resilience4j ile Devre Kesiciler
  2. Yeniden Denemeleri ve Zaman Aşımlarını Yapılandırma
  3. Hataları Ele Alma ve Geri Dönüşler
  4. Dayanıklılık için Bölme Yalıtımı ve Hız Sınırlama
← API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) Sayfasına Dön