Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure custom error pages for exceptions in view files?

We're using UseStatusCodePagesWithReExecute in combination with a simple custom middleware that sets Response.StatusCode to 500, to successfully to send users to our custom error page on exceptions that occur in mvc controllers.

However, for exceptions that occur in razor/cshtml views, UseStatusCodePagesWithReExecute doesn't send the user to our error page (though our custom middleware does detect these exceptions in Invoke()).

We tried using an Exception Filter as well, but it only traps exceptions from controller actions, not from views.

Is there a way to send users to our error page if the exception originates in a view?

like image 597
user1543181 Avatar asked Dec 14 '25 02:12

user1543181


1 Answers

StatusCodePagesMiddleware added by UseStatusCodePagesWithReExecute extension call has the following check after executing of underlying middlewares:

// Do nothing if a response body has already been provided.
if (context.Response.HasStarted
    || context.Response.StatusCode < 400
    || context.Response.StatusCode >= 600
    || context.Response.ContentLength.HasValue
    || !string.IsNullOrEmpty(context.Response.ContentType))
{
    return;
}

When rendering of the View starts, MVC middleware fills Response.ContentType with text/html value. That's why above check returns true and request with status code page is not re-executed.

The fix is fair simple. In your middleware that handles exceptions, call Clear() method on Response:

public async Task InvokeAsync(HttpContext context)
{
    try
    {
        await _next(context);
    }
    catch (Exception)
    {
        context.Response.Clear();
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
}

Sample Project on GitHub

like image 113
CodeFuller Avatar answered Dec 16 '25 23:12

CodeFuller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!