উদাহরণ সহ Exception Handling

Java Technologies - স্প্রিং বুট ক্লায়েন্ট (Spring Boot Client) - Error Handling এবং Exception Management
151

Spring Boot WebClient বা RestTemplate ব্যবহার করে API-তে রিকোয়েস্ট পাঠানোর সময় বিভিন্ন ধরনের সমস্যা দেখা দিতে পারে, যেমন Timeout, Invalid Response, Authentication Failure, ইত্যাদি। এই সমস্যাগুলো মোকাবিলা করার জন্য Exception Handling একটি অপরিহার্য বিষয়। নিচে Spring Boot Client এর মাধ্যমে Exception Handling এর উদাহরণ দেখানো হয়েছে।


Exception Handling এর প্রয়োজনীয় ধাপ:

  1. Custom Exception তৈরি করুন।
  2. WebClient বা RestTemplate এর জন্য Exception Handling যুক্ত করুন।
  3. Globally Exception Handle করার জন্য @ControllerAdvice ব্যবহার করুন।

১. Custom Exception তৈরি করা

public class ApiException extends RuntimeException {
    public ApiException(String message) {
        super(message);
    }
}

২. WebClient ব্যবহার করে Exception Handling

WebClient এর মাধ্যমে API কল এবং Exception Handling:

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("https://api.example.com").build();
    }

    public String fetchData() {
        try {
            return webClient.get()
                    .uri("/data")
                    .retrieve()
                    .onStatus(
                            status -> status.is4xxClientError() || status.is5xxServerError(),
                            response -> {
                                String errorMessage = "Error: " + response.statusCode();
                                return response.bodyToMono(String.class)
                                        .map(body -> new ApiException(errorMessage + " - " + body));
                            }
                    )
                    .bodyToMono(String.class)
                    .block(); // Blocking for simplicity (avoid in production)
        } catch (WebClientResponseException ex) {
            throw new ApiException("WebClient Response Error: " + ex.getMessage());
        } catch (Exception ex) {
            throw new ApiException("An unexpected error occurred: " + ex.getMessage());
        }
    }
}

৩. RestTemplate ব্যবহার করে Exception Handling

RestTemplate এর মাধ্যমে API কল এবং Exception Handling:

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {

    private final RestTemplate restTemplate;

    public RestTemplateService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData() {
        String url = "https://api.example.com/data";
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (HttpClientErrorException | HttpServerErrorException ex) {
            throw new ApiException("RestTemplate Error: " + ex.getStatusCode() + " - " + ex.getResponseBodyAsString());
        } catch (Exception ex) {
            throw new ApiException("An unexpected error occurred: " + ex.getMessage());
        }
    }
}

৪. Global Exception Handling

Spring Boot-এ @ControllerAdvice ব্যবহার করে Exception Handling কে কেন্দ্রীয়ভাবে পরিচালনা করা যায়।

Global Exception Handler:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ApiException.class)
    public ResponseEntity<String> handleApiException(ApiException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGenericException(Exception ex) {
        return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

৫. Example Execution

API Call Example:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements CommandLineRunner {

    private final ApiService apiService;

    public AppRunner(ApiService apiService) {
        this.apiService = apiService;
    }

    @Override
    public void run(String... args) {
        try {
            String response = apiService.fetchData();
            System.out.println("API Response: " + response);
        } catch (ApiException ex) {
            System.err.println("Handled Exception: " + ex.getMessage());
        }
    }
}

৬. উদাহরণ রেসপন্স

Success Response:

{
  "data": "This is the API response."
}

Error Response (Handled by Exception Handler):

{
  "error": "RestTemplate Error: 404 NOT_FOUND - Resource not found"
}

Exception Handling Best Practices:

  1. Custom Exception ব্যবহার করুন: প্রজেক্টের মধ্যে স্পষ্ট বার্তা দিতে কাস্টম এক্সসেপশন ব্যবহার করুন।
  2. Proper HTTP Status Return করুন: কনজিউমারদের জন্য উপযুক্ত HTTP স্ট্যাটাস কোড ব্যবহার করুন।
  3. Global Handling: @ControllerAdvice ব্যবহার করে অ্যাপ্লিকেশনের প্রতিটি এক্সসেপশন এক জায়গায় ম্যানেজ করুন।
  4. Reactive Handling: WebClient ব্যবহার করলে Non-blocking Exception Handling ব্যবহার করুন।

এভাবে Exception Handling ইমপ্লিমেন্ট করে আপনি API এর ত্রুটিগুলো আরও সহজে এবং কার্যকরভাবে পরিচালনা করতে পারবেন।

Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...