Skip to content

ImageKit client with RawResponses throws on Request errors #76

@matteo-gregoricchio-deltatre

Description

Hello all,

When using the .NET SDK with RawResponses, I received ImageKitExceptions when some operations failed.
Is this expected?

@imagekitio

Seeing that the Response from the RawResponses client contains StatusCode, I supposed that it wouldn't throw on error.

Steps to reproduce

Using .NET10 SDK, save the following code to a .cs file and run it with dotnet run. Replace with your account private key and the fileId the two variables.

#:sdk Microsoft.NET.Sdk.Web
#:package Imagekit@6.*
#:property PublishAot=false

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Imagekit;
using Imagekit.Core;
using Imagekit.Exceptions;
using Imagekit.Models.Files;

using var client = new ImageKitClient(
    new ClientOptions
    {
        BaseUrl = "https://api.imagekit.io",
        PrivateKey = "your-private-key"
    });

const string err = "If I'm there, I threw an exception :(";

// EXAMPLE 1
try
{
    var fakeFileId = "6a14828c5c7cd75eb8dac858";
    var metadata = await client
    .WithRawResponse
    .Files
    .Metadata
    .Get(fakeFileId)
    .ConfigureAwait(false);

    Console.WriteLine($"I won't get there 'cause this will throw... {metadata.IsSuccessStatusCode}");
}
catch (ImageKitNotFoundException exc)
{
    Console.WriteLine(err, exc.Message);
    Console.WriteLine(exc.Message);
}

// EXAMPLE 2
try
{
    var fileUploadParams = new FileUploadParams
    {
        // file will be a stream with the URL, send with content-type: form-data 
        File = new BinaryContent()
        {
            Stream = new MemoryStream(Encoding.UTF8.GetBytes("https://picsum.photos/id/237/200/300")),
            ContentType = MediaTypeHeaderValue.Parse("multipart/form-data")
        },
        FileName = "a file name",
        Folder = "test",
        IsPrivateFile = false,
        UseUniqueFileName = true,
        Checks = Checks()
    };
    static string Checks()
    {
        const string mimeTypeCheckKey = "'file.mime' IN";
        var admittedMimeTypes = JsonSerializer.Serialize(new string[] { "video/3gpp2", "image/gif" });

        return $"{mimeTypeCheckKey} {admittedMimeTypes}";
    }

    var metadata = await client
    .WithRawResponse
    .Files
    .Upload(fileUploadParams)
    .ConfigureAwait(false);

    Console.WriteLine($"I won't get there 2 'cause this will throw... {metadata.IsSuccessStatusCode}");
}
catch (ImageKitBadRequestException exc2)
{
    Console.WriteLine(err);
    Console.WriteLine(exc2.Message);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions