jasontaylordev / NorthwindTraders

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use ProblemDetails/ValidationProblemDetails etc for exception middleware?

zyofeng opened this issue · comments

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);
    }

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