kiota: Take exception message from OpenAPI document

Today, when a non-successful status code is returned (which is described in the OpenAPI document), an exception is thrown with an unhelpful generic message:

Exception of type 'MyProject.Models.ErrorResponseDocument' was thrown.

In contrast, NSwag takes the message from the OpenAPI document.

For comparison, here are my test assertions from Kiota:

var exception = (await action.Should().ThrowExactlyAsync<ErrorResponseDocument>()).Which;
exception.ResponseStatusCode.Should().Be((int)HttpStatusCode.Conflict);
exception.Message.Should().Be($"Exception of type '{typeof(ErrorResponseDocument).FullName}' was thrown.");
exception.Errors.ShouldHaveCount(1);

Compared with those from NSwag:

var exception = (await action.Should().ThrowExactlyAsync<ApiException<ErrorResponseDocument>>()).Which;
exception.StatusCode.Should().Be((int)HttpStatusCode.Conflict);
exception.Message.Should().Be("HTTP 409: The request body contains conflicting information or another resource with the same ID already exists.");
exception.Result.Errors.ShouldHaveCount(1);

Here’s the OpenAPI fragment the code was generated against:

"responses": {
  "400": {
    "description": "The query string is invalid or the request body is missing or malformed.",
    "content": {
      "application/vnd.api+json": {
        "schema": {
          "$ref": "#/components/schemas/errorResponseDocument"
        }
      }
    }
  },
  "409": {
    "description": "The request body contains conflicting information or another resource with the same ID already exists.",
    "content": {
      "application/vnd.api+json": {
        "schema": {
          "$ref": "#/components/schemas/errorResponseDocument"
        }
      }
    }
  },
  "422": {
    "description": "Validation of the request body failed.",
    "content": {
      "application/vnd.api+json": {
        "schema": {
          "$ref": "#/components/schemas/errorResponseDocument"
        }
      }
    }
  }
}

And, for reference, our shared ApiException class we point NSwag to, where we format the exception message by prefixing it with the HTTP status code (note: the constructor signatures are prescribed by NSwag):

// We cannot rely on generating ApiException as soon as we are generating multiple clients, see https://github.com/RicoSuter/NSwag/issues/2839#issuecomment-776647377.
// Instead, we configure NSwag to point to the exception below in the generated code.

namespace JsonApiDotNetCore.OpenApi.Client.NSwag;

public class ApiException(string message, int statusCode, string? response, IReadOnlyDictionary<string, IEnumerable<string>> headers, Exception? innerException)
    : Exception($"HTTP {statusCode}: {message}", innerException)
{
    public int StatusCode { get; } = statusCode;
    public virtual string? Response { get; } = string.IsNullOrEmpty(response) ? null : response;
    public IReadOnlyDictionary<string, IEnumerable<string>> Headers { get; } = headers;
}

public sealed class ApiException<TResult>(
    string message, int statusCode, string? response, IReadOnlyDictionary<string, IEnumerable<string>> headers, TResult result, Exception? innerException)
    : ApiException(message, statusCode, response, headers, innerException)
{
    public TResult Result { get; } = result;
    public override string Response => $"The response body is unavailable. Use the {nameof(Result)} property instead.";
}

So, to summarize, would it be possible for Kiota to use the text from the OpenAPI document as the Exception.Message value of the generated exception class? It should be a parameter (like in NSwag), because the same exception type could be used for multiple status codes (each with a different message).

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 16 (10 by maintainers)

Most upvoted comments

Thanks for your invaluable input, these (painful) verbatims help shape internal decisions.

When I asked if we could work together, the response should have been: “We can approve/reject proposals, but you’ll have to do all the work yourself because we’re currently not interested in serving the needs of outside developers”

I don’t think this is a fair representation of the situation for multiple reasons:

  • situations change, since you’ve originally reached out, we’ve been re-org’d 3 times. Not that it should be your concern, but it helps explain some of the impact here.
  • when we set out to build “yet another REST API code generator”, I personally made a point to developing it as an open source project, and in such a way that it’s a tool that any API consumer can have a great experience with. You couldn’t imagine how many prior internal only initiatives lived and died because they didn’t follow this path. You couldn’t imagine how many Graph specific scenarios would have been much easier to implement if we have taken Graph specific shortcuts, and we had lots of influent people advocating to do so internally.
  • we have a successful track record of collaborating with the community to at least take the feedback in, and at best ensure their contributions get merged in swiftly.

Yes, our staffing challenges show up through multiple aspects (lack of documentation, some issues are not being addressed as fast as we’d like given other priorities, etc…), and this is one of the growing pains we’ve been trying to address with mitigated success.

I found a few other quirks and oddities in kiota, but I don’t see the point of taking the time to report them anymore

Please do if you can find the energy, being the devil’s advocate here, even if we (Microsoft) didn’t do anything with those issues in the short term, it’d be a central point for others to tack on, and let us know this is something that needs attention, helping prioritize work in the mid-term.

Every created issue is read many times by others, without ever responding

If you can find issues where we haven’t responded at all, please ping me personally on those. Throughout the staffing issues, we’ve made a point to ensuring every issue at least gets an initial reply and triaged. If a few items fell through the cracks, reminding us about those is always a net benefit for everyone.

Because NSwag was recently abandoned, now is the window of opportunity to invest heavily in kiota

This, and other generators being abandoned over the last 18 months, I believe proves the point that delivering a great code generation experience takes backing from an important industry player with vested interests in the API space. Which is what we’re doing. These efforts represent, in my opinion, too much work to be supported by the community only (which is why we didn’t go with any personal account to address your earlier comment). And the only sustainable alternative to those two models are paid for, generally closed source, venture capital, startup, kind of initiatives. Which I don’t believe would put the community in a better place.

I know those kinds of conversations can feel tense sometimes due to the lossy nature of aync/text-only media. We value your general feedback, and our replies are here to provide good-hearted context. ❤️

I think I can say with some confidence that having a “developer friendly” message is irrelevant. It’s the least of our worries. Developer care about the type of the exception and the content of any payload that may be sent with that exception.

Totally agree. We need access to the technical bits. We’ll translate it to a localized UI message, based on what the user tried to do and how he/she should proceed.

The flaw here is that it is assumed that the callers of the API are at all able to ask the team of the API to adjust their OpenAPI specification for this.

Yes, this is usually not feasible. It’s brought up frequently, a more pragmatic approach would help. We shouldn’t fall off the cliff when the world isn’t perfect.

At the risk of repeating myself, a better design (which is an improvement over even NSwag) would be to define a generic ApiException:

As far as I’m aware, this is already how NSwag works (and I’m happy with it). ApiException<TModel> derives from ApiException, which provides access to the status code, headers, and (the first few KBs of) the payload, which is great for log correlation. It doesn’t need reflection, just generates the appropriate construction code:

 if (status_ == 400)
 {
     var objectResponse_ = await ReadObjectResponseAsync<ErrorResponseDocument>(response_, headers_, cancellationToken).ConfigureAwait(false);
     if (objectResponse_.Object == null)
     {
         throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
     }
     throw new ApiException<ErrorResponseDocument>("The query string is invalid.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null);
 }
 else
 {
     var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
     throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
 }

In the snippet above, the text “The query string is invalid.” originates from the description in the OpenAPI document and is mapped to the Exception.Message property. If there is no mapping (the else clause), you’ll get (the first few KBs of) the payload, which is great to log an HTTP 500 that contains HTML.

So yes, I feel your pain. There is something wrong with the design of Kiota, at least as far as exception handling is concerned. … But I didn’t expect to invest so much time for such a simple issue.

Thanks. I’ve hit many odd designs in Kiota over the past 6 months. When you bring it up, it either gets dismissed without motivation, or a long thread starts (based on incomprehension or theoretical dilemmas), without being heard. When you’re at the point of giving up, the issue is closed as completed. A very frustrating experience indeed. I don’t think there’s bad intent, just a lack of understanding what app developers typically need (combined with stubbornness), and not knowing how to foster a community. Surely kiota has a long way to go, but code can be refactored and redesigned, so that would just be a matter of time. It’s the attitude (and the continuous misunderstandings) that make me give up.

the term extension here is referring to OpenAPI specification extensions.

Thank you. That clears it up.

So…

Respectfully, from our point of view (and I write “our” since I speak not only for myself), there are 3 design flaws here, the third being the direct consequence of the other two.

Flaw 1:

Kiota is able to get a “developer friendly” error message from the payload (https://github.com/microsoft/kiota/issues/4349#issuecomment-2210946079)

I’m a developer. “We” are a group of about 100 .NET developers at our company. I think I can say with some confidence that having a “developer friendly” message is irrelevant. It’s the least of our worries. Developer care about the type of the exception and the content of any payload that may be sent with that exception. Any friendly messages are for any exception propagated to the user/client that will end up in the UI if at all relevant and possible (in a multi-language environment, issuing a friendly message in the appropriate language has its own challenges). Any other stuff is either dealt with or logged via structured logging. But “friendly developer messages”? No, we don’ care. Having a design that forces you to use an extension to accomplish something we’re not interested in is flawed.

Flaw 2:

…only if an extension has been added to the description to let Kiota know which property to use (https://github.com/microsoft/kiota/issues/4349#issuecomment-2210946079)

The flaw here is that it is assumed that the callers of the API are at all able to ask the team of the API to adjust their OpenAPI specification for this. Next to .NET, we also have Java and other tech platform teams exposing APIs. I don’t think asking them to modify their spec with an extension just because we want to use a tool that requires it to do something is going to fly. Even asking other .NET teams to do so will be met with blank stares. No tool should force you to do that. So we won’t add extensions to OpenAPI specs for something we don’t care about.

If that was all there was, it would end here: we’re not interested in friendly developer messages, nor in extensions. So we can just ignore it. Alas, the design of Kiota in view of the above flaws automatically generate a third flaw which we can’t ignore:

Flaw 3: inheriting from ApiException

I totally agree with @darrelmiller: forcing a model to inherit from ApiException is the fundamental flaw in the design. There is no good reason to do this, and it forces the code generation to work around potential conflicts of property names. The correction of https://github.com/microsoft/kiota/issues/4893 may cause the code to compile, but the design flaw remains.

The problem of course is that even if you’re not interested in friendly developer messages, your models will still inherit from ApiException if they are used in an error return.

A model can be used either as a legitimate return payload, or as a payload from an error status code. I’m not saying this is good design, but it’s allowed. Making models inherit from Exception (directly or indirectly) just because they are used in an error return is (in our opinion) wrong and just plain confusing.

At the risk of repeating myself, a better design (which is an improvement over even NSwag) would be to define a generic ApiException:

public class ApiException<TModel>: ApiException
{
    public TModel Model { get; }

    public ApiException(TModel model)
    {
        Model = model;
    }

    public ApiException(TModel model, string message)
    : base(message)
    {
        Model = model;
    }

    public ApiException(TModel model, string message, Exception innerException)
    : base(message, innerException)
    {
        Model = model;
    }
}

And somewhere (I would make it a static method in the ApiException class) we would have:

public class ApiException
{
    // existing implementation here //


    public static ApiException CreateException(object model)
    {
        ArgumentNullException.ThrowIfNull(model);
        var type = typeof(ApiException<>).MakeGenericType(model.GetType());
        return (ApiException)Activator.CreateInstance(type, model)!;
    }

    public static ApiException CreateException(object model, string message)
    {
        ArgumentNullException.ThrowIfNull(model);
        var type = typeof(ApiException<>).MakeGenericType(model.GetType());
        return (ApiException)Activator.CreateInstance(type, model, message)!;
    }
}

Then the code in https://github.com/microsoft/kiota-http-dotnet/blob/6c1e799f63a26b9209e7153d7f1eb2d2c730e9f6/src/HttpClientRequestAdapter.cs#L381 can be rewritten to look like this:

if(result is not Exception ex)
{
     var apiException = ApiException.CreateException(result, $"The server returned an unexpected status code and the error registered for this code failed to deserialize: {statusCodeAsString}");
     apiException.ResponseStatusCode = statusCodeAsInt,
     apiException.ResponseHeaders = responseHeadersDictionary
    throw apiException;
}

This would return a correctly model-typed exception containing a (hopefully meaningful) model instance returned from the API. That information (i.e. the result in the code) would otherwise be lost.

There are two extra thoughts (and yes, I’m repeating myself again):

  • Activator.CreateInstance doesn’t exactly have stellar performance, but this is used for the exceptional flow, so I think performance is OK in this scenario. We can avoid metaprogramming by introducing an extra interface, but let’s not go there for now.
  • API controllers in .NET support Problem Details, it would be interesting to think about how this “fits” with this design.

Is this the best design possible? No, of course not. But any design that doesn’t force your models to inherit from anything outside of their own OpenAPI definition is, in my view, an improvement. No more special code that renames properties behind your back.

C# developers want the best C# code generation. Java developers want the best Java code generation. Go developers want the best Go code generation. Nobody cares about the “other” development languages or tech platforms except its own. OpenAPI is the common spec. If the intermediate abstraction from which the code is generated isn’t able to do that for all languages, then it’s not rich/good enough.

And no, I won’t submit a PR. This is a design problem, not a code problem.

Because NSwag was recently abandoned, now is the window of opportunity to invest heavily in kiota. Primarily as a tool with excellent support for .NET and TypeScript (and awesome IDE integrations, which Microsoft is loved for). We hardly care about the other languages. OpenAPI originated in the .NET ecosystem, that’s where most of its users are. Explaining why progress is so slow helps me understand, but does not motivate me to invest in kiota. Pretty sad.

We are also desperate to find a good alternative to NSwag because the ability to generate code from OpenAPI is crucially important. We can’t live without this functionality, and we suspect few people are. Moving from NSwag 13 to 14 was (and still is) painful.

There were internal discussions at my company about the best way to proceed given our limited resources. There is no problem in contributing to a project in our limited way, even in monetary terms. But we also encountered problems that lead to an incomprehension of the design decisions made by the Kiota team. It’s funny that it was also regarding error handling. See https://github.com/microsoft/kiota/issues/4893: don’t let the title of the issue fool you, it was a different title and they changed it.

So yes, I feel your pain. There is something wrong with the design of Kiota, at least as far as exception handling is concerned. They talk about “using the right extensions” but without pointing to any realistic example. I’m glad it’s not just me who are encountering problems even for trivial APIs.