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)
Thanks for your invaluable input, these (painful) verbatims help shape internal decisions.
I don’t think this is a fair representation of the situation for multiple reasons:
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.
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.
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.
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. ❤️
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.
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.
As far as I’m aware, this is already how NSwag works (and I’m happy with it).
ApiException<TModel>derives fromApiException, 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:In the snippet above, the text “The query string is invalid.” originates from the
descriptionin the OpenAPI document and is mapped to theException.Messageproperty. If there is no mapping (theelseclause), you’ll get (the first few KBs of) the payload, which is great to log an HTTP 500 that contains HTML.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.
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:
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:
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
ApiExceptionI totally agree with @darrelmiller: forcing a model to inherit from
ApiExceptionis 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
ApiExceptionif 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:And somewhere (I would make it a static method in the
ApiExceptionclass) we would have:Then the code in https://github.com/microsoft/kiota-http-dotnet/blob/6c1e799f63a26b9209e7153d7f1eb2d2c730e9f6/src/HttpClientRequestAdapter.cs#L381 can be rewritten to look like this:
This would return a correctly model-typed exception containing a (hopefully meaningful) model instance returned from the API. That information (i.e. the
resultin the code) would otherwise be lost.There are two extra thoughts (and yes, I’m repeating myself again):
Activator.CreateInstancedoesn’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.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.
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.