aspnetcore: Add InternalServerError and InternalServerError to TypedResults
Summary
As a .NET developer who develops a lot of Web API:s, I often use the new TypedResults with return type Result<T1, T2, …>. In every project that I use this, I find myself implementing a custom return type of InternalServerError and InternalServerError<TValue> since it’s missing in the standard implementation.
Motivation and goals
If I’m using TypedResults, I’m doing that for two major reasons:
- Compile time errors for return types that doesn’t match the intended design (specified in the return type of the method)
- Autogeneration of metadata for OpenAPI specification
In scope
- You want to be able to have a 500 Internal Server error containing a complex type as one of your possible return types for your endpoint and get compile time errors if it doesn’t match what you’re actually returning.
- You want the return type of 500 Internal Server Error containing the complex type to be described in your autogenerated OpenAPI specification, so that your clients knows what to expect.
- Same as above, but a 500 Internal Server Error with no content.
Risks / unknowns
This can be misused as a general return type for client errors, but I feel like that is more of a violation of REST rather than the framework.
Examples
Simplified example:
app.MapGet("/books/{id}", async Task<Results<Ok<Book>, NotFound<string>, InternalServerError<string>>> (int id) => {
try
{
// Retrieve the book
var book = await ...
if (book is null)
return TypedResults.NotFound($"Could not find book with id: {id}");
// Found book
return TypedResults.Ok(book);
}
catch (Exception ex)
{
Log.Error($"Something unexpected happened: {ex}");
return TypedResults.InternalServerError("Something unexpected happened while processing your request, please contact the API provider");
}
});
Detailed design
Looking at the other TypedResults, I would implement this as follows:
/// <summary>
/// An <see cref="IResult"/> that on execution will write an object to the response
/// with Internal Server Error (500) status code.
/// </summary>
public sealed class InternalServerError : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult
{
/// <summary>
/// Initializes a new instance of the <see cref="InternalServerError"/> class with the values
/// provided.
/// </summary>
internal InternalServerError()
{
}
/// <summary>
/// Gets the HTTP status code: <see cref="StatusCodes.Status500InternalServerError"/>
/// </summary>
public int StatusCode => StatusCodes.Status500InternalServerError;
int? IStatusCodeHttpResult.StatusCode => StatusCode;
/// <inheritdoc/>
public Task ExecuteAsync(HttpContext httpContext)
{
ArgumentNullException.ThrowIfNull(httpContext);
// Creating the logger with a string to preserve the category after the refactoring.
var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Result.InternalServerErrorObjectResult");
HttpResultsHelper.Log.WritingResultAsStatusCode(logger, StatusCode);
httpContext.Response.StatusCode = StatusCode;
return Task.CompletedTask;
}
/// <inheritdoc/>
static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder)
{
ArgumentNullException.ThrowIfNull(method);
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status500InternalServerError, typeof(void)));
}
}
… and
/// <summary>
/// An <see cref="IResult"/> that on execution will write an object to the response
/// with Internal Server Error (500) status code.
/// </summary>
/// <typeparam name="TValue">The type of error object that will be JSON serialized to the response body.</typeparam>
public sealed class InternalServerError<TValue> : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult<TValue>
{
/// <summary>
/// Initializes a new instance of the <see cref="InternalServerError"/> class with the values
/// provided.
/// </summary>
/// <param name="error">The error content to format in the entity body.</param>
internal InternalServerError(TValue? error)
{
Value = error;
HttpResultsHelper.ApplyProblemDetailsDefaultsIfNeeded(Value, StatusCode);
}
/// <summary>
/// Gets the object result.
/// </summary>
public TValue? Value { get; }
object? IValueHttpResult.Value => Value;
/// <summary>
/// Gets the HTTP status code: <see cref="StatusCodes.Status500InternalServerError"/>
/// </summary>
public int StatusCode => StatusCodes.Status500InternalServerError;
int? IStatusCodeHttpResult.StatusCode => StatusCode;
/// <inheritdoc/>
public Task ExecuteAsync(HttpContext httpContext)
{
ArgumentNullException.ThrowIfNull(httpContext);
// Creating the logger with a string to preserve the category after the refactoring.
var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Result.InternalServerErrorObjectResult");
HttpResultsHelper.Log.WritingResultAsStatusCode(logger, StatusCode);
httpContext.Response.StatusCode = StatusCode;
return HttpResultsHelper.WriteResultAsJsonAsync(
httpContext,
logger: logger,
Value);
}
/// <inheritdoc/>
static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder)
{
ArgumentNullException.ThrowIfNull(method);
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status500InternalServerError, typeof(TValue), new[] { "application/json" }));
}
}
I would open a PR, but the code of conduct said to post a design proposition first.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 17
- Comments: 20 (18 by maintainers)
API Review notes:
InternalServerErrormethod toTypedResultsas wellInternalServerErrorvariant that includes an exception?The API that’s been proposed so far has been approved!
Updated API:
I’ve added a PR for this issue, hoping it will be picked up by someone at the ASP.NET team. Glad to see that others find this useful as well!
I’m happy to see that you have approved my API proposal. Thank you guys for being kind and helpful throughout the process! I’ve updated the PR and removed the overload that includes an exception. Also, I learned a lot by looking at the code in this repo. 😊
Here are some of my thoughts on your notes from the review:
500 Internal Server Erroris a response type that indicates to the consumer of an API that an unexpected error happened, preventing the API from fufulfilling the request. Of course this is not desirable, but I would argue that it is indeed a scenario that can and (given enough time) probably will happen. And when that happens, it’s nice to have prepared the consumer for how such a response will look. Will it contain aProblemDetails? Or maybe just astringwith some error text? Whichever one it is, the consumer now has a better chance to understand how to handle it. Maybe I’m wrong, but I have always considered the503 Service Unavailableto be caused by some expected reason, like planned maintenance or something. And of course,400 Bad Requestwould assume that the consumer did something wrong.So, lets take a look at this code:
It will give the following compile-time error:
This is because
BadRequestis not specified as a valid response type inResults<T1, T2, ...>, which in turn makes sure that I cannot return a response type that is not represented in my OpenAPI specification. This is the same exact thing I want to achieve withInternalServerError.With all that said, these are just my opinions and thoughts. That does not necessarily mean that they are correct.
Btw, is it possible to say when this change will be made available?
Thanks for waiting. After some internal discussion, our API review feedback is to take back what we said earlier when we suggested we should have another
InternalServerErrorvariant that includes an exception, so that we could hook into exception handling and the problem details middleware."API Review Notes:
Ultimately, we decided to approve the API without the Exception stuff for now. If we decide later that we were wrong to exclude Exception overloads, we can still add it then.
@onurmicoogullari Thanks! I’ll send this in for API review now.
Hmmm…I’m not opposed to adding another constructor to the existing
InternalServerErrortype. We’ll have to see how that fairs in API review but I’m comfortable championing that shape.Yep! Then we’ll review the API shape in the issue for the follow-up.
Yes, please!
Another thing we discussed was adding an new overload of
InternalServerErrorthat took anExceptiontype that would be re-thrown for handling by the exception handling and problem details middlewares but allowed an endpoint to participate in the OpenAPI metadata generation.Let me know if you need any help modifying the API/PR with these changes.
@MackinnonBuck Awesome! I must’ve missed adding it to
TypedResults. Should I update my PR to adhere to the change requests suggested by your review?