How to Handle API Errors When Using ChatGPT in C#?

 Error handling can be done using try-catch blocks and checking the HTTP response status. Here's an example:

public static async Task<string> GetChatGPTResponse(string prompt)
{
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var requestBody = new
        {
            model = "text-davinci-003",
            prompt = prompt,
            max_tokens = 150
        };

        var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");

        try
        {
            var response = await httpClient.PostAsync(endpoint, content);

            if (!response.IsSuccessStatusCode)
            {
                var errorResponse = await response.Content.ReadAsStringAsync();
                throw new Exception($"API call failed with status code: {response.StatusCode}. Response: {errorResponse}");
            }

            var responseBody = await response.Content.ReadAsStringAsync();
            dynamic result = JsonConvert.DeserializeObject(responseBody);
            return result.choices[0].text;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Request error: {e.Message}");
            return "Error calling ChatGPT API.";
        }
        catch (Exception e)
        {
            Console.WriteLine($"General error: {e.Message}");
            return "An unexpected error occurred.";
        }
    }
}


This example provides better error handling for network issues and API-specific errors.

Comments

Popular posts from this blog

How to Convert Word Document to PDF using C#

Sql query to get counts by quarterly and half yearly

How to Get First Day and Last Day of a Current Quarter in SQL Server