mardi 30 novembre 2021

Global Error Handling in ASP.NET Core MVC

I tried to implement a global error handler on my Asp.net core mvc web page. For that I created an error handler middleware like described on this blog post.

    public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception error)
        {
            var response = context.Response;
            response.ContentType = "application/json";

            switch (error)
            {
                case KeyNotFoundException e:
                    // not found error
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    break;
                default:
                    // unhandled error
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }

            var result = JsonSerializer.Serialize(new { message = error?.Message });
            await response.WriteAsync(result);
            context.Request.Path = $"/error/{response.StatusCode}"; // <----does not work!
        }
    }
}

The middleware works as expected and catches the errors. As a result i get a white page with the error message. But i am not able to display a custom error page. I tried it with the following line of code. But this does not work.

context.Request.Path = $"/error/{response.StatusCode}";

Any ideas how I can achive my goal?

Thanks in advance




Aucun commentaire:

Enregistrer un commentaire