Home > Blockchain >  Global Error Handling in ASP.NET Core MVC
Global Error Handling in ASP.NET Core MVC

Time:12-01

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

CodePudding user response:

It seems that you wish to redirect the browser to an error page.

To do this you'll need to replace:

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

With

context.Reponse.Redirect($"/error/{response.StatusCode}");

Also, since you're sending a redirect, the response content needs to be empty, so remove the response.WriteAsync bit too.

var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);
  • Related