Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify exception throwing #39

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .fernignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ LICENSE.md
src/AssemblyAI/AssemblyAI.csproj
src/AssemblyAI/Core/ClientOptions.cs
src/AssemblyAI/Core/JsonConfiguration.cs
src/AssemblyAI/Core/ExtendedRawClient.cs
src/AssemblyAI/ClientOptions.cs
src/AssemblyAI/Constants.cs
src/AssemblyAI/UserAgent.cs
Expand Down
6 changes: 4 additions & 2 deletions src/AssemblyAI.IntegrationTests/LemurTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using AssemblyAI.Core;
using AssemblyAI.Lemur;

Expand Down Expand Up @@ -82,17 +83,18 @@ public async Task Should_Generate_Task()
}

[Test]
[Ignore("Ignore until fixed")]
//[Ignore("Ignore until fixed")]
public void Should_Fail_To_Generate_Summary()
{
var client = new AssemblyAIClient(ApiKey);
var ex = Assert.ThrowsAsync<BadRequestError>(async () => await client.Lemur.SummaryAsync(new LemurSummaryParams
var ex = Assert.ThrowsAsync<HttpOperationException>(async () => await client.Lemur.SummaryAsync(new LemurSummaryParams
{
FinalModel = LemurModel.Basic,
TranscriptIds = ["bad-id"],
AnswerFormat = "one sentence"
}).ConfigureAwait(false));

Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That(ex.Message, Is.EqualTo("each transcript source id must be valid"));
}

Expand Down
11 changes: 0 additions & 11 deletions src/AssemblyAI/Core/AssemblyAIClientException.cs

This file was deleted.

23 changes: 23 additions & 0 deletions src/AssemblyAI/Core/AssemblyAIException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;

#nullable enable

namespace AssemblyAI.Core;

/// <summary>
/// Base exception class for all exceptions thrown by the SDK.
/// </summary>
public class AssemblyAIException : Exception
{
public AssemblyAIException()
{
}

public AssemblyAIException(string message) : base(message)
{
}

public AssemblyAIException(string message, Exception innerException) : base(message, innerException)
{
}
}
42 changes: 42 additions & 0 deletions src/AssemblyAI/Core/ExtendedRawClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Net.Http;
using System.Text.Json;

namespace AssemblyAI.Core;

#nullable enable

public partial class RawClient
{
private partial async Task OnResponseErrorAsync(HttpResponseMessage response){
var responseContentString = await response.Content.ReadAsStringAsync()
.ConfigureAwait(false);
if (string.IsNullOrEmpty(responseContentString))
{
throw new HttpOperationException(
$"Error with status code {response.StatusCode}",
response.StatusCode,
responseContentString
);
}

try
{
var error = JsonUtils.Deserialize<AssemblyAI.Error>(responseContentString);
throw new HttpOperationException(
error.Error_,
response.StatusCode,
responseContentString
);
}
catch (JsonException)
{
}

// use response content as error message if error object cannot be deserialized
throw new HttpOperationException(
responseContentString,
response.StatusCode,
responseContentString
);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using AssemblyAI.Core;

#nullable enable
Expand All @@ -7,16 +8,16 @@ namespace AssemblyAI.Core;
/// <summary>
/// This exception type will be thrown for any non-2XX API responses.
/// </summary>
public class AssemblyAIClientApiException(string message, int statusCode, object body)
: AssemblyAIClientException(message)
public class HttpOperationException(string message, HttpStatusCode statusCode, string responseContent)
: AssemblyAIException(message)
{
/// <summary>
/// The error code of the response that triggered the exception.
/// </summary>
public int StatusCode { get; } = statusCode;
public HttpStatusCode StatusCode { get; } = statusCode;

/// <summary>
/// The body of the response that triggered the exception.
/// </summary>
public object Body { get; } = body;
public string ResponseContent { get; } = responseContent;
}
27 changes: 22 additions & 5 deletions src/AssemblyAI/Core/RawClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;

namespace AssemblyAI.Core;

Expand All @@ -8,7 +10,7 @@ namespace AssemblyAI.Core;
/// <summary>
/// Utility class for making raw HTTP requests to the API.
/// </summary>
public class RawClient(
public partial class RawClient(
Dictionary<string, string> headers,
Dictionary<string, Func<string>> headerSuppliers,
ClientOptions clientOptions
Expand All @@ -24,6 +26,8 @@ ClientOptions clientOptions
/// </summary>
private readonly Dictionary<string, string> _headers = headers;

private partial Task OnResponseErrorAsync(HttpResponseMessage response);

public async Task<ApiResponse> MakeRequestAsync(BaseApiRequest request)
{
var url = BuildUrl(request);
Expand All @@ -32,21 +36,25 @@ public async Task<ApiResponse> MakeRequestAsync(BaseApiRequest request)
{
request.Headers.Add("Content-Type", request.ContentType);
}

// Add global headers to the request
foreach (var header in _headers)
{
httpRequest.Headers.Add(header.Key, header.Value);
}

// Add global headers to the request from supplier
foreach (var header in headerSuppliers)
{
httpRequest.Headers.Add(header.Key, header.Value.Invoke());
}

// Add request headers to the request
foreach (var header in request.Headers)
{
httpRequest.Headers.Add(header.Key, header.Value);
}

// Add the request body to the request
if (request is JsonApiRequest jsonRequest)
{
Expand All @@ -63,10 +71,18 @@ public async Task<ApiResponse> MakeRequestAsync(BaseApiRequest request)
{
httpRequest.Content = new StreamContent(streamRequest.Body);
}

// Send the request
var httpClient = request.Options?.HttpClient ?? Options.HttpClient;
var httpClient = request.Options?.HttpClient ?? Options.HttpClient
?? throw new Exception("No HttpClient provided in request or client options");
var response = await httpClient.SendAsync(httpRequest);
return new ApiResponse { StatusCode = (int)response.StatusCode, Raw = response };
if (!response.IsSuccessStatusCode)
{
await OnResponseErrorAsync(response).ConfigureAwait(false);
}

var apiResponse = new ApiResponse { StatusCode = response.StatusCode, Raw = response };
return apiResponse;
}

public record BaseApiRequest
Expand Down Expand Up @@ -107,7 +123,7 @@ public record JsonApiRequest : BaseApiRequest
/// </summary>
public record ApiResponse
{
public required int StatusCode { get; init; }
public required HttpStatusCode StatusCode { get; init; }

public required HttpResponseMessage Raw { get; init; }
}
Expand Down Expand Up @@ -140,10 +156,11 @@ private string BuildUrl(BaseApiRequest request)
{
current += $"{queryItem.Key}={queryItem.Value}&";
}

return current;
}
);
url = url.Substring(0, url.Length - 1);
return url;
}
}
}
18 changes: 0 additions & 18 deletions src/AssemblyAI/Exceptions/BadRequestError.cs

This file was deleted.

17 changes: 0 additions & 17 deletions src/AssemblyAI/Exceptions/GatewayTimeoutError.cs

This file was deleted.

18 changes: 0 additions & 18 deletions src/AssemblyAI/Exceptions/InternalServerError.cs

This file was deleted.

17 changes: 0 additions & 17 deletions src/AssemblyAI/Exceptions/NotFoundError.cs

This file was deleted.

17 changes: 0 additions & 17 deletions src/AssemblyAI/Exceptions/ServiceUnavailableError.cs

This file was deleted.

18 changes: 0 additions & 18 deletions src/AssemblyAI/Exceptions/TooManyRequestsError.cs

This file was deleted.

18 changes: 0 additions & 18 deletions src/AssemblyAI/Exceptions/UnauthorizedError.cs

This file was deleted.

Loading
Loading