jasontaylordev / NorthwindTraders

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.
MIT License
5k stars 1.59k forks source link

Use ProblemDetails/ValidationProblemDetails etc for exception middleware? #268

Closed zyofeng closed 2 years ago

zyofeng commented 4 years ago

Something like this? Also I understand for aspnetcore 3.0 has abstracted the JsonSerializer so it is agnostic for both System.TextJson and Json.NET? Probably a good idea to incorporate that?

    private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var result = string.Empty;
        switch (exception)
        {
            case ValidationException ex:
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                result = JsonSerializer.Serialize(new ValidationProblemDetails(ex.Failures));
                break;
            case BadRequestException ex:
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                result = JsonSerializer.Serialize(new ProblemDetails { Title = ex.Message });
                break;
            case UserAccessViolation _:
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                break;
            case NotFoundException _:
                context.Response.StatusCode = StatusCodes.Status404NotFound;
                break;
            case Exception ex when !isProd:
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                result = JsonSerializer.Serialize(new ProblemDetails { Title = ex.Message });
                break;
        }

        context.Response.ContentType = "application/json";

        return context.Response.WriteAsync(result);
    }
zyofeng commented 2 years ago

I have ended up using ProblemDetailsMiddleware, this is no longer needed