Codit / practical-api-guidelines

Practical guidelines for building & designing APIs with .NET.
MIT License
16 stars 5 forks source link

Serialization and Accept header #102

Open MassimoC opened 5 years ago

MassimoC commented 5 years ago

Shouldn't we let ASP.NET handle the serialization of the error in the format that is specified by the accept header of the request instead of deciding for ourselves that it should always be json ? _Originally posted by @fgheysels


        public static void UseExceptionHandlerWithProblemJson(this IApplicationBuilder applicationBuilder)
        {
            applicationBuilder?.UseExceptionHandler(errorApplication =>
            {
                errorApplication.Run(async context =>
                {
                    var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                    var exception = errorFeature.Error;

                    var errorDetail = context.Request.IsLocalRequest()
                        ? exception.Demystify().ToString()
                        : "The instance value should be used to identify the problem when calling customer support";

                    var problemDetails = new ProblemDetailsError
                    {
                        Title = "An unexpected error occurred!",
                        Status = StatusCodes.Status500InternalServerError,
                        Detail = errorDetail,
                        Instance = $"urn:codit.eu:server-error:{Guid.NewGuid()}"
                    };

                    // TODO: Plug in telemetry
                    context.Response.WriteJson(problemDetails, contentType: ContentTypeNames.Application.JsonProblem);
                });
            });
        }
pietersap commented 5 years ago

My 2 cents: If the changes in #109 are implemented, then 4XX errors are serialized to XML if requested in the header. Even without making changes in the code above.

This is not true for the 5XX errors...

MassimoC commented 5 years ago

102 and #109 are the same issue. Keep in mind that problem+xml should be inline with the RFC https://tools.ietf.org/html/rfc7807#page-10 (e.g. default ns should be added)